Some maths problems from .NET 4.72 and earlier are still present in .NET Core 2.2, also Dictionary problem in .NET 4.72

by Patrick Lee on 01 May 2019 in categories tech with tags ASP.NET 4.72 ASP.NET Core dictionary maths

Silent failures from some common maths operations in .NET Core 2.2 (and earlier), and .NET 4.72 (and earlier)

For many years, I and colleagues have been aware that the treatment of maths in .NET (and even before that in C++) can lead to code failing silently.

That is: the code stops working normally, but instead of stopping and letting the user know that there is a problem, it continues running, but with incorrect (or at least unexpected) output.

This happens with several things including divide by zero (where the code returns infinity and continues running) and log of zero or a negative number (where the code returns NaN, not a number, and continues running).

The work around has been to be aware of these problems and use custom functions to detect the problem and report it as soon as it occurs.

If you (or your developers) don't do that, then your code could well be failing silently, which is bad because your output may be incorrect, and:

  1. You or your customers may not notice it, and
  2. Even if you notice it, you will have to step through your code to find the (possibly many) places where the problem occurs.

I had noticed that .NET Core 2.2 (and 2.1, and possibly earlier versions too) had fixed a problem with .NET 4.72 and earlier's Dictionary class, and had hoped that along with that fix, .NET Core would have also fixed the above maths problems. 

But on investigation, this does not seem to be the case.

I have published a short code repository on GitHub to show this - see here.

A problem with the Dictionary in .NET 4.72 and earlier

(For non technical readers, a Dictionary is a collection of key, value pairs, where the keys have to be unique.)

The Dictionary problem in .NET 4.72 and earlier is that if you ask for a value in the Dictionary corresponding to a key that doesn't exist (e.g. 2), then instead of telling you the useful information (e.g. "You asked for a value for key 2, which doesn't exist in the dictionary"), .NET 4.72 and earlier misses out the important information. It just says "The given key was not present in the dictionary".

MathAndDictionaryProblemsInDotNet4.72...

See the repository for the full code, but a screenshot of the relevant code for .NET Core 2.2 Console App project is:

CodeScreenshotMathProblemsStillPresen...

Other developers: I'd be interested to hear of your reactions to this (maybe I'm missing something and it isn't a problem, but at the moment I don't think so), and other ways of addressing the issues.