tags:

views:

130

answers:

3

How would one go about implementing the indexing "operator" on a class in C# ?

class Foo {

}

Foo f = new Foo();
f["key"] = "some val";
f["other key"] = "some other val";

in C# ? Searched MSDN but came up empty.

+4  A: 
    private List<string> MyList = new List<string>();
    public string this[int i]
    {
        get
        {
            return MyList[i];
        }
        set
        {
            MyList[i] = value;
        }

    }

You can define several accessors for different types (ie string instead of int for example) if it's needed.

Brann
+4  A: 

Here is an example using a dictionary as storage:

public class Foo {

 private Dictionary<string, string> _items;

 public Foo() {
  _items = new Dictionary<string, string>();
 }

 public string this[string key] {
  get {
   return _items[key];
  }
  set {
   _items[key]=value;
  }
 }

}
Guffa
+2  A: 

There called Indexers or sometimes Indexer Properties.

Here's the MSDN page about them.

Cameron MacFarland
ah, so that's the name - hate when you know what you want and how it should work, and you know it's possible because you seen it + done it a whole lot of other languages ... you just don't know the name of it on this platform.
thr
I know exactly what you mean. That's why I thought I'd submit this answer although others had already given the syntax. Glad it helped.
Cameron MacFarland