Wednesday, August 15, 2007

C# ? operator - Nullable shorthand

The Nullable structure is a new generic structure to C# 2.0 which allows null values for value types (reference types obviously support this). This is useful in avoiding the magical "-1"'s and such.

The C# 2.0 compiler also provides a handy shorthand operator for this - ?.

To define a nullable integer you use one of the following statements:

Nullable<int> nullInt = new Nullable<int>();
Nullable<int>nullInt = new Nullable<int>(2); // Initialzie to 2


int? nullInt;
int? nullInt = 2;

Console.WriteLine(nullInt.HasValue ? nullInt.Value.ToString() : "NULL!");

Very handy!

No comments: