Wednesday, April 2, 2008

Nullable Types

Value types (such as int) cannot be made null. This code:
int age = null;
will produce an error that says, Cannot convert source type 'null' to target type 'int'.

Now you can convert value types to a nullable type by using a question mark (?) right after the type declaration:
int? age = null; 
if (age != null) DoSomething(); 
//or 
if (age.HasValue) DoSomething(); 
Nullable types expose a new boolean HasValue property.

Now you don't have to agree upon a "standard" representation of a null condition, invalid value or an uninitialized value for your reference types. Like saying, everytime you see a -1 for this int, it means nothing was returned or that your int has no value.

More Info: MSDN: Nullable Types