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.
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.
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.
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;
}
}
}
There called Indexers or sometimes Indexer Properties.
Here's the MSDN page about them.