Archive for the ‘Nullable Types’ tag
Brief Hints: C# Nullable Types and Arrays, Special Double Values
Brief Hints: I wanted to show you three things in C# that I’ve been using a lot lately.
Nullable Types are a convenient language construction in C# that allows one to assign a primitive type with null…
double? someval = null; // declares a nullable double called 'someval'.
The question mark suffixing the keyword double makes the variable someval nullable. This was originally designed so that one can retrieve values from LINQ to SQL without checking for nulls (SQL inherently makes this distinction). This could be thought of as yet another construct to make autoboxing primitives more intuitive and more entrenched in the language.
I use nullable types when I need a special ‘unassigned’ value for “find the greatest” or “find the least” kinds of loops.
When we apply Nullable Types to Arrays, we get an array of nullable primitives (arrays are already nullable, being first class objects).
double?[] somevals = new double?[10]; // declares an array called 'somevals' of ten nullable doubles.
An array of primitives is initialized with all values 0.0; whereas an array of primitve?s is initialized with nulls.
Special Double Values are also something that I’ve started using a lot. There are many algorithms I’ve been coming across that use “magic numbers” corresponding to arbitrarily high and arbitrarily low numbers. Instead of using evil magical quantities, I’ve been using Double.PositiveInfinity and Double.NegativeInfinity. C# makes it easy to assign three more special quantities: Double.NaN, Double.MinValue and Double.MaxValue.
Edit: I forgot to mention why I kept italicizing the word primitive. C# doesn’t really have primitives that are exposed to the developer– everything actually IS an object, and the illusion of boxing or not isn’t really relevant. This just makes nullable types all the more logical.