Doing some code reading and stumbled upon this snippet that I haven't seen before:
public SomeClass {
public someInterface this[String strParameter] {
get {
return SomeInternalMethod(strParameter);
}
}
}
It looks like it is called as follows:
SomeClass _someClass = new SomeClass();
SomeInterface returnedValue = _someClass["someString"];
I am interested in where this function would be appropriate or what the intent of writing in this style. For example why would this be preferred over simply calling the function?
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:
It seems like a lot of the answers are focusing on what an indexer is, not why you would want to use one.
As far as I'm concerned, here is the motivation to use an indexer:
You are working on a class that has a collection of some sort, but you want the class to appear to users (consumers of the class) as if it is a collection.
The best example I can think of is the DataRow
class in ADO.NET. If you want to get the value of the fifth cell of a DataRow
, you can either use DataRow.Item[4]
or DataRow[4]
. The latter form is a convenient and logical shortcut, and it shows off pretty nicely why you'd want to use an indexer. To the user, the DataRow
can be thought of as just a collection of cells (even though it is really more than that), so it makes sense to be able to get and set cell values directly, without having to remember that you are actually getting/setting an Item
.
Hope that helps.
In many cases, the 'index' syntax makes a lot of sense. It is particularly useful if the SomeClass represents some sort of collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With