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.

Give Types an Index

Scenario/Problem: Your type has data values that can be accessed by some kind of index, either numerical or string based.

Solution: You can index by any type. The most common index types are int and string.

Implement a Numerical Index

You use the array access brackets to define an index on the this object, like this sample:

public double this[int index]
{
    get
    {
        switch (index)
        {
            case 0: return _x;
            case 1: return _y;
            case 2: return _z;
            default: throw new ArgumentOutOfRangeException("index",
                "Only indexes 0-2 valid!");
        }
    }
    set
    {
        switch (index)
        {
            case 0: _x = value; break;
            case 1: _y = value; break;
            case 2: _z = value; break;
            default: throw new ArgumentOutOfRangeException("index",
                "Only indexes 0-2 valid!");
        }
    }

}

Implement a String Index

Unlike regular arrays, however, you are not limited to integer indices. You can use any type at all, most commonly strings, as in this example:

public double this[string dimension]
{
    get
    {
        switch (dimension)
        {
            case "x":
            case "X": return _x;
            case "y":
            case "Y": return _y;
            case "z":
            case "Z": return _z;
            default: throw new ArgumentOutOfRangeException("dimension",
                "Only dimensions X, Y, and Z are valid!");
        }
    }
    set
    {
        switch (dimension)
        {
            case "x":
            case "X": _x = value; break;
            case "y":
            case "Y": _y = value; break;
            case "z":
            case "Z": _z = value; break;
            default: throw new ArgumentOutOfRangeException("dimension",
                "Only dimensions X, Y, and Z are valid!");
        }
    }

}

Sample usage:

Vertex3d v = new Vertex3d(1, 2, 3);
Console.WriteLine(v[0]);
Console
.WriteLine(v["Z"]);

Output:

1
3

Total Pages : 12 678910

comments