Monday, February 25, 2008

[.NET] Nullable Types - Go forth and nullify

A very useful and not-so-common feature of .NET built-in types is they're NULLABLE. This feature has been introduced with .NET 2.0 and comes in quite handy when you wanna be able to tell if a value has not been assigned (e.g. this can be used instead of the old ugly
–2147483648 trick for int32 and so on).

in C# you can use either:

Nullable<bool> myNullableBool = null;

or:
bool? myNullableBool = null;

If you declare a variable as nullable you can then use the HasValue method to evaluate wether tha value has been assigned or not, like this:

if (myNullableBool.HasValue)
{ /* My bool is an average true/false*/ }
else
{ /*oh My! My bool is NULL!*/ }

In VB the declaration syntax is slightly different, and actually it looks like shit (but just keep in mind the OMEN: we all -sooner or later- will have to deal with VB):
Dim MyNullableBool As Nullable(Of Boolean) = Nothing

Ok, now all you gotta do -if you feel like it- is ... go forth and nullify!

No comments: