Suppose I have an array or any other collection for that matter in class and a property which returns it like following:
public class Foo
{
public IList<Bar> Bars{get;set;}
}
Now, may I write anything like this:
public Bar Bar[int index]
{
get
{
//usual null and length check on Bars omitted for calarity
return Bars[index];
}
}
Like functions, Indexers can also be overloaded. In C#, we can have multiple indexers in a single class. To overload an indexer, declare it with multiple parameters and each parameter should have a different data type. Indexers are overloaded by passing 2 different types of parameters.
Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.
Which among the following are the advantages of using indexers? Explanation: Indexers provides a view at large scale to visualize a collection of items as an array. It is really easy to use the object of the class that represents a collection as if it is an array.
The main difference between Indexers and Properties is that the accessors of the Indexers will take parameters. In the above syntax: access_modifier: It can be public, private, protected or internal.
No - you can't write named indexers in C#. As of C# 4 you can consume them for COM objects, but you can't write them.
As you've noticed, however, foo.Bars[index]
will do what you want anyway... this answer was mostly for the sake of future readers.
To elaborate: exposing a Bars
property of some type that has an indexer achieves what you want, but you should consider how to expose it:
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