Wednesday, October 11, 2006

.NET 2.0 and VS 2005 - Nullable Value Types

We're finally getting some training on .NET 2.0 at work. I'll be posting things that I find interesting in the next couple of days.

One of the first things that I really liked is the ability to have nullable value types. For example, let's say that you have an integer for tracking some value and it can be positive and negative. It is also possible for the value to be not set yet. How do you detect that the value hasn't been set yet? You typically come up with some arbitrary number like 99999999 and hope that the real value is never actually 999999999. In .NET 2.0, they have the ? syntax that allows you to set a value type (ie int, long, struct, etc) to null. For example the following code would not compile in 1.1 but works wonderfully in 2.0:

class MyClass
{
private int? someValue;

public MyClass()
{
someValue = null;
}
public int GetSomeValue()
{
if( someValue != null )
{
return someValue;
}
else
throw new Exception( "Some Value has not been set" );
}
}

This is a much cleaner and safer way than checking for some arbitrary number like 999999999.

2 comments:

Anonymous said...

Welcome to a whole new world my friend! Other new methods you might find useful: String.IsNullOrEmtpy() and type.TryParse()

Anonymous said...

if( someValue != null )
{
return someValue;
}

Can also be written like:

if(someValue.HasValue)
{
return someValue.Value;
}