Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Allow Value Type to Be Null

Scenario/Problem:

You need to assign null to a value type to indicate the lack of a value. This scenario often occurs when working with databases, which allow any data type to be null.

Solution:

This isn’t technically something you need to implement in your class. .NET 2.0 introduced the Nullable<T> type, which wraps any value type into something that can be null. It’s useful enough that there is a special C# syntax shortcut to do this. The following two lines of code are semantically equivalent:

Nullable<int> _id;
int? _id;

Let’s make the _id field in our Vertex3d class Nullable<T> to indicate the lack of a valid value. The following code snippet demonstrates how it works:

struct Vertex3d : IFormattable, IEquatable<Vertex3d>,
                  IComparable<Vertex3d>
{
    private int? _id;

    public int? Id
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value;
        }
    }
    ...
}
...
Vertex3d vn = new Vertex3d(1, 2, 3);
vn.Id = 3;      //ok
vn.Id = null;   //ok
try
{
    Console.WriteLine("ID: {0}", vn.Id.Value);//throws
}
catch (InvalidOperationException)
{
    Console.WriteLine("Oops--you can't get a null value!");
}

if (vn.Id.HasValue)
{
    Console.WriteLine("ID: {0}", vn.Id.Value);
}
  • + Share This
  • 🔖 Save To Your Account