Nullables in .NET

I don’t know if you’ve ever had a problem with trying to store a null value in a value type in .NET.  If you have, you may be interested to know that there is a generic type wrapper in .NET which can sort the problem out.  It is called Nullable.

You can use it like this (in VB.NET)

Dim n as Nullable(of Integer)

You can then use the HasValue property on it to see if it has a value, and the Value property to retrieve the value.  You can also assign to and from it as normal, including assigning Nothing/null to it.

No related posts.

Tags: , , , ,

2 Responses to “Nullables in .NET”

  1. Jon says:

    In C# it’s similar – you declare the variable as e.g. Nullable<int> n;

    However, you can also use the following notation:
    int? n;

    The ‘?’ is short-hand for ‘Nullable’.

  2. [...] Studio 2008 or whether I just missed it completely in 2005, but I have just noticed that you can do Nullables in VB.NET the same way you can in [...]

Leave a Reply