Tuesday, October 20, 2009

Nullable types

A new language construct as of the .NET 2.0 Framework is Nullable types. Basically, it allows one to extend a Value Type (such as int, bool), and make it nullable.

Here's a small sample class I wrote to experiment with using Nullable Types.


namespace Project
{
public class DataTest
{
// The syntax T? (in C#) is shorthand for System.Nullable<T>, where T is a value type. The two forms are interchangeable.
private int? age = null;
private System.Nullable<system.int32> weight = null;

public int? Age
{
get { return age; }
set { age = value; }
}

public int? Weight
{
get { return weight; }
set { weight = value; }
}

public DataTest()
{}

public DataTest(int? myAge, int? myWeight)
{
Age = myAge;
Weight = myWeight;
}

///
/// Return String displaying age and weight
///

///
public override string ToString()
{
if (Age.HasValue && Weight.HasValue)
{
return "Your age is: " + Age.Value + ", and your weight is: " + Weight.Value;
}
else
{
return "No age or weight entered";
}
}
}
}


The following is a good reference for Nullable Types: Introduction to .Net Framework 2.0 Nullable Types.

No comments:

Post a Comment