views:

1693

answers:

4

I would like to add an operator to a class. I currently have a GetValue() method that I would like to replace with an [] operator.

class A
{
    private List<int> values = new List<int>();

    public int GetValue(int index)
    {
        return values[index];
    } 
}
+19  A: 
public int this[int key]
{
    get
    {
        return GetValue(key);
    }
    set
    {
        SetValue(key,value);
    }
}
m0rb
+13  A: 

I believe this is what you are looking for:

Indexers (C# Programming Guide)

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get
        {
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = 
            new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}
William Brendel
+2  A: 
public int this[int index]
    {
        return values[index];
    }
BFree
+4  A: 

The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.

For example, in your case where an int is the key or index:

public int this[int index]
{
  get
  {
     return GetValue(index);
  }
}

You can also add a set accessor so that the indexer becomes read and write rather than just read-only.

public int this[int index]
{
  get
  {
     return GetValue(index);
  }

  set
  {
    SetValue(index, value);
  }
}

If you want to index using a different type, you just change the signature of the indexer.

public int this[string index]
...
Jeff Yates