Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is named indexer property possible? [duplicate]

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 image 642
TheVillageIdiot Avatar asked Jul 20 '10 19:07

TheVillageIdiot


People also ask

Can a class have multiple indexers?

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.

What is indexer property in C#?

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?

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.

Can indexer be private?

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.


1 Answers

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:

  • Do you want callers to be able to replace the collection with a different collection? (If not, make it a read-only property.)
  • Do you want callers to be able to modify the collection? If so, how? Just replacing items, or adding/removing them? Do you need any control over that? The answers to those questions would determine what type you want to expose - potentially a read-only collection, or a custom collection with extra validation.
like image 148
Jon Skeet Avatar answered Nov 15 '22 10:11

Jon Skeet