Nullable Types in C# 2.0
I'm teaching a C# 2.0 class at Interface Technical Training this week and thought I'd blog about two features I really like in C# 2.0 that save some typing (although they may arguably lead to more cryptic code) and are really useful. Sure, there's all the goodness associated with generics, anonymous methods, partial types, etc. in C# 2.0 but two nice language enhancements are nullable types (which relate to generics) and the ?? operator. If you've ever retrieved a null value from a database and then tried to assign it to an int or DateTime variable then you'll definitely appreciate nullable types if you haven't already used them.
Nullable types can be defined in different ways. The first is using the Nullable<T> struct which is new in .NET 2.0:
Nullable<int> age = GetAge();
While this works, I prefer the following syntax which is the same as the code above but more compact:
int? age = GetAge();
I also like the ?? operator since it provides a compact way to check if a variable is null. If the value is null then a default value can be returned. Instead of the writing the following code to check for nulls (which uses short-cut conditional logic):
int? tempAge = (age==null)?-1:age;
I could instead use the ?? operator:
int? tempAge = age??-1;
The code that uses the ?? operator says that if age isn't null then assign it to tempAge. If age is null then assign tempAge a value of -1. Some may argue that this makes code too cryptic (and they'd have a point). But, I like compact coding solutions. Besides....it's not nearly as bad as writing regular expressions. :-)