Thursday, May 22, 2008

[C#] Nullable Types

I bumped into this in my web travels today: Nullable types. Introduced in the 2.0 .NET framework was the ability to represent the normal range of values for a given value type PLUS the null value.

Nullable types can only be VALUE types [including structs]. It cannot be applied to reference types. Syntactically they look as follows:
  • T? // Is actually shorthand for...
  • System.Nullable // A struct - see below for its properties.


Ex. int? or System.Nullable

The nullable struct brings with it two readonly properties:
  • HasValue: Returns true if the variable contains a value, and false if null.
    • ex. Can use (x.HasValue) or (x != null) pretty much interchangeably.
  • Value: Returns the value if one is assigned or throws an InvalidOperationException if not assigned. Often this function is used to help cast a nullable type to a non nullable type.
ex.
// Correct
int? iNull = null;

// Will not compile
int notNull = iNull;

// Will compile, but exc thrown if null.
int notNull2 = iNull.Value;


When using operators on nullable values, the result will be a null if any of the operands are null. When comparing nullables, if one of the values is null then the comparison is always FALSE.

Often used with Nullable types is the ?? operator. It returns the left-hand operand if it is not null, or else it returns the right operand.

int? iNull = null; int iNull2 = null;

// notNull will receive the value -1.
int notNull = iNull ?? -1;

// Can use the ?? multiple times...
int notNull2 = iNull ?? iNull2 ?? -1;


If using bool? then the variable may not be used in conditionals like if, or for. The code will not compile.

Reference MSDN

No comments: