Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/forums/c-sharp/)
-   -   Give Types an Index (http://www.go4expert.com/forums/types-index-t21339/)

arunlalds 13Mar2010 15:11

Give Types an Index
 
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:
Code:

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:
Code:

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:
Code:

Vertex3d v = new Vertex3d(1, 2, 3);
Console.WriteLine(v[0]);
Console.WriteLine(v[“Z”]);
Output:
1
3



All times are GMT +5.5. The time now is 07:34.