Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexer as part of the interface in C#

In C#, what's the syntax for declaring an indexer as part of an interface? Is it still this[ ]? Something feels odd about using the this keyword in an interface.

like image 403
Dinah Avatar asked Aug 03 '09 17:08

Dinah


People also ask

Can an interface have indexers?

Indexers can be declared on an interface. Accessors of interface indexers differ from the accessors of class indexers in the following ways: Interface accessors do not use modifiers.

CAN interface have indexers like class?

Like a class, Interface can have methods, properties, events, and indexers as its members.

What is indexer 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.

What is the use of indexer?

Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access as an array. The compiler will generate an Item property (or an alternatively named property if IndexerNameAttribute is present), and the appropriate accessor methods.


3 Answers

public interface IYourList<T>
    {
        T this[int index] { get; set; }
    }
like image 173
Stan R. Avatar answered Oct 20 '22 08:10

Stan R.


It is - it's pretty odd syntax at other times if you ask me! But it works. You have to declare the get; and/or set; parts of it with no definition, just a semi-colon, exactly like ordinary properties in an interface.

like image 21
Daniel Earwicker Avatar answered Oct 20 '22 10:10

Daniel Earwicker


I know what you mean but, yes, this is correct. Here are the docs.

like image 36
Ben Griswold Avatar answered Oct 20 '22 10:10

Ben Griswold