Doing some code reading and stumbled upon this snippet that I haven\'t seen before:
public SomeClass {
public someInterface this[String strParameter] {
See the language specification, section 10.9, which states:
An Indexer is a member that enables an object to be indexed in the same way as an array.
Indexers and properties are very similar in concept, but differ in the following ways:
That's called an Indexer, they allow you to use List<>, ArrayList, Dictionary<> and all the other collections using an array syntax.
It's just syntactic sugar, but it gives some readability when used right.
You may have already stumbled across something similar before:
var myList = new List<string>();
myList.Add("One");
myList.Add("Two");
myList.Add("Three");
for(int i = 0; i < myList.Count; i++) {
string s = myList[i];
}
The indexer is the "primary key" of an object that implements a collection. It's just a shorthand way for writing a function like .GetValue(index) - syntactic sugar, if you want. But it also makes the intent clear.
In many cases, the 'index' syntax makes a lot of sense. It is particularly useful if the SomeClass represents some sort of collection.
It an implementation of the index operator [ ]
.
In my opinion, it's just a syntax convenience. Where would you NOT use it:
public SomeClass {
private int[] nums;
public GetVal this[int ind] {
get {
return nums[ind]; // this is pointless since array is already indexed
}
}
}
Where would you benefit from it:
public Matrix {
private Dictionary<string, double> matrixData; // Matrix indecies, value
public double this[int row, int col] {
get {
return matrixData[string.Format("{0},{1}", row, col)];
}
}
}
As you can see, for some reason, your data is a Dictionary indexed with a string key and you wish to call this with two integer indecies and still do not want to change your data type:
Matrix m = new Matrix();
...
Console.WriteLine( m[1,2] );