Thursday, July 23, 2009

Nullable

When declaring a value type (int, bool, char, DateTime, etc.) you cannot initialize it to null or you'll get this error message: To fix this you need to declare your variable as nullable:
Nullable<bool> answer1 = null;
// or
bool? answer2 = null;
When this is done, 2 new properties become available to you, HasValue and Value. Now you can check if your variable has been assigned a value yet or if it's still null with HasValue.
if (answer1.HasValue) Console.WriteLine("answer1 is {0}", answer1);


More Info: MSDN: Nullable(T) Structure