thoughts on nullable types

Posted by Jake Good
on Nov 22, 05

So in .Net 2.0 they added nullable types to the CLR. Which essentially equates to value types having null value instead of a default value.



Which is great and not-so-great.



Great




  1. Database integration. Databases have nullable columns, so why not let classes have them?


  2. Nullable dates. DateTime being a value type in .Net, has always been a pain for keeping nullable dates. Using object as the type (breaking strong typing) or using MinDate or MaxDate as null dates (BAD!).


  3. When you have a class that actually needs nullable types. It’s one of those conveniences (almost syntactic sugar)




Not So Great




  1. When you see a value from a class that could be a nullable type, you have to check and prepare for that.


  2. More work for the consumer of your type isn’t always the best way to deal with things.




There are a few .Net tricks to overcome some of these obstacles and make nullable types useful.



for instance…



String has a static method to help…



String.IsNullOrEmpty(randomString)


System.Nullable has…



type.HasValue


null coalescing operator (default value if null)



int? x = (random potentially nullable int);  
int? y = (random potentially nullable int);
int? z = x ?? y;
int i = z ?? -1;
Comments

Leave a response

  1. Andy GaskellNov 22 05 @ 02:18AM
    (y) for nullable types
  2. blameMikeNov 22 05 @ 02:18AM
    Nullable types are hot.
Comment