1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Give Types an Index

Discussion in 'C#' started by arunlalds, Mar 13, 2010.

  1. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    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
    
     

Share This Page