After Robert mentioned that we will be moving to a newer version of the .NET framework, I wanted the opportunity to look at some of the language improvements of .NET 2.0 specifically the use of nullable types.


There are two main types that we generally deal with, reference and value types. These two types are treated and stored differently and as a result we have specific behaviors that go along with these types. The main difference I would like to highlight is the fact that value types cannot be null.

So for example:-

int x = 0; //legal
int x = null; // not so legal "Cannot convert null to 'int' because it is a value type"
string s = "hello"; //legal
string s = null; //legal

The surface response is that integers are never null ... but development with XSD and Sql Server allows  us to have nullable integers. So there are legitimate reasons to have a strong solution for this problem of null values.


The first way we could do this is to actually create a class that wraps round the integer type. This class would support a series of methods that would checks for Null values. I saw a great VB 6 developer do a similar thing. However, this approach is made redundant in .NET 2.0.


Nullable Template:
The more appropriate way to do this would be to use the new Nullable struct This gives us the following:

Nullable<int> i = null; //legal

We can also use HasValue to determine whether the current value is null as follows:

Nullable<int> i = null
if(i.HasValue)  //(also i==null would work)
    int j = (int)i;

This can be rewritten as follows:

int? i = null; // int ? => nullable int
int j = i ?? 0;

Check the last two snippets of code out in ILDASM. It really amounts to the same thing.

Technorati tags: