Using Nullable Types in C#
Comparisons occur in a similar manner to the mathematical operations. The operands in a comparison are lifted to both being nullable. Then, the comparison is done. If one of the operands contains a null, the result of the comparison will be false.
If comparing for equality (or non-equality), two variables containing null will be considered equal. A variable containing null compared to a variable with any value will be considered not equal. The following are some examples of comparisons:
int abc = 123;int xyz = 890;int? def = null;int? uvw = 123;Comparison Resultabc == xyz // falseabc == def // falsedef == null // trueabc == uvw // trueuvw == null // falseuvw != null // true
Comparison Resultabc > uvw // false, they are equalabc < def // false, def is nulluvw < def // false, because def is nulldef > null // false, because right side is nulluvw > null // false, because right side is null
C# also gets an additional operator in its newest version. This is the ?? operator used for null coalescing. The null coalescing operator takes the following format:
returnValue = first ?? second;
In this case, if first is not null, its value will be returned to returnValue. If first is null, then the value of second will be returned. You should note that returnValue can be either a nullable or non-nullable variable.
If you wanted to move a nullable varaible's value to a non-nullable version, you could do the following:
int? ValA= 123;int? ValB = null;int NewVarA = ValA ?? -1;int NewVarB = ValB ?? -1;
When the above is completed, NewVarA will contain the value of 123 because ValA was not null. NewVarB will contain the value of -1 because ValB was null. As you can see, this allows you to change variables with a null value to a defaulted value. In this case, the defaulted value is -1.
In conclusion, the newest version of C# allows for a nullable type. These types can be used with non-nullable types with little thought and little effort because the conversions will be built into the language. The nullable types should make working with database records and other optional information much easier going forward.
Nullable types is a part of the ECMA-334 version of C#. You'll need a compiler that supports this C# standard in order to use nullable types. Visual Studio 2005 supports this standard.
# # #
About the Author
Bradley Jones is a Microsoft MVP that works for Jupitermedia as an Executive Editor over many of the software development sites and channels. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days.
Page 2 of 2