New Features in C# 2.0—Nullable Types: What just happened?
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
What just happened?
Let’s focus on the Main method. Five nullable types are created:
int? myNullableInt = 25; double? myNullableDouble = 3.14159; bool? myNullableBool = null; // neither yes nor no // string? myNullableString = "Hello"; // Dog? myNullableDog = new Dog(3);
The first three are perfectly valid, but you cannot create a nullable string or a nullable user-defined type (class), and thus they should be commented out.
However, structs can be user defined, and it’s OK to use them as nullables.
|
We check whether each nullable type is null (or, equivalently, whether
the HasValue property is true). If so, we print their value (or equivalently,
we access their Value property).
After this the value null is assigned to myNullableInt:
myNullableInt = null;
The next line would like to declare an integer and initialize it with the
value in myNullableInt, but this is not legal; there is no implicit conversion
from a nullable int to a normal int. You can solve this in two ways.
The first is with a cast:
b = (int)myNullableInt;
This will compile, but it will throw an exception at runtime if
myNullableInt is null (which is why we’ve enclosed it in a try/catch
block).
The second way to assign a nullable int to an int is to provide a default
value to be used in case the nullable int is null:
int c = myNullableInt ?? -1;
This line reads as follows: "initialize int c with the value in myNullableInt
unless myNullableInt is null, in which case initialize c to -1."
Comparison operators always return false if one value is null!
|
It turns out that all the comparison operators (>, <, <=, etc.) return false if
either value is null. Thus, a true value can be trusted:
if (myNullableInt >= c) { Console.WriteLine("myNullableInt is greater than or equal to c"); }
| W A R N I N G |
Note, however, that == will return true if both arguments are null.
|
If the statement "myNullableInt is greater than or equal to c" displays,
you know that myNullableInt is not null, nor is c, and that
myNullableInt is greater than c. However, a false value cannot be
trusted in the normal fashion:
else { Console.WriteLine("Is myNullableInt less than c?"); }
This else clause can be reached if myNullableInt is less than c, but it
can also be reached if either myNullableInt or c is null.
|

