C# what is the point or benefit of an indexer?
c#, indexer, methods
Solution
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:
- A property is identified by its name, whereas an indexer is identified by its signature.
- A property is accessed through a simple-name (§7.5.2) or a member-access (§7.5.4), whereas an indexer element is accessed through an element-access (§7.5.6.2).
- A property can be a static member, whereas an indexer is always an instance member.
- A get accessor of a property corresponds to a method with no parameters, whereas a get accessor of an indexer corresponds to a method with the same formal parameter list as the indexer.
- A set accessor of a property corresponds to a method with a single parameter named value, whereas a set accessor of an indexer corresponds to a method with the same formal parameter list as the indexer, plus an additional parameter named value.
- It is a compile-time error for an indexer accessor to declare a local variable with the same name as an indexer parameter.
- In an overriding property declaration, the inherited property is accessed using the syntax base.P, where P is the property name. In an overriding indexer declaration, the inherited indexer is accessed using the syntax base[E], where E is a comma separated list of expressions.
Problem
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?