FREE BOOK

Chapter 2: Creating Versatile Types

Posted by SAMS Publishing Free Book | C# Language March 24, 2010
Tags: C#
This chapter is all about making your own objects as useful and versatile as possible. In many cases, this means implementing the standard interfaces that .NET provides or simply overriding base class methods.

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);

}

Total Pages : 12 89101112

comments