Monday, June 15, 2009

Nullable Types

It's our friend from C#, and is a language construct for use with value types (such as int, long, double, byte, bool, etc).

int? iCanBeNull = null;

Perfectly good code, you can use nullable types for referring to data values that come across from the DB as null. This helps keep "garbage" out of the database.

How do you use them in if statements?

if( iCanBeNull.HasValue && iCanBeNull.Value > 57)
{
   //do some stuff
}

The compiler does autoboxing too (implicit conversion of nullable type to value type), but be careful! Booleans can't be used in "if" statements the same way any more, since a nullable boolean may have three values {true|false|null}. You have to instead use

if(nullableBool.Value) //works, but throws exception if it's null
{
   //do some other stuff
}
//this is bad for the compiler
if(nullableBool) //compiler error CS0266
{
   //never compiles?
}


Steffi! more input?
http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx
http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx
http://blogs.msdn.com/ericgu/archive/2004/05/27/143221.aspx

No comments:

Post a Comment