Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "this[0]" mean in C#?

Tags:

c#

I was going through some library code and saw a method like:

public CollapsingRecordNodeItemList List {     get { return this[0] as CollapsingRecordNodeItemList; } } 

The class that contains this method is not a list or something iterable, so what exactly does this[0] mean?

like image 472
Cemre Mengü Avatar asked May 20 '13 13:05

Cemre Mengü


2 Answers

Look for an indexer in the class.

C# lets you define indexers to allow this sort of access.

Here is an example from the official guide for "SampleCollection".

public T this[int i]     {         get         {             // This indexer is very simple, and just returns or sets              // the corresponding element from the internal array.              return arr[i];         }         set         {             arr[i] = value;         }     } 

Here is the definition from the official language specification:

An indexer is a member that enables objects to be indexed in the same way as an array. An indexer is declared like a property except that the name of the member is this followed by a parameter list written between the delimiters [ and ]. The parameters are available in the accessor(s) of the indexer. Similar to properties, indexers can be read-write, read-only, and write-only, and the accessor(s) of an indexer can be virtual.

One can find the full and complete definition in section 10.9 Indexers of the specification.

like image 130
Benjamin Gruenbaum Avatar answered Oct 10 '22 16:10

Benjamin Gruenbaum


It means that the declaring type (or a base-class of that) has an "indexer" which presumably takes an int (or similar) and returns... something (perhaps object ?). The code calls the indexer's get accessor, passing 0 as the index - and then treats the returned value as a CollapsingRecordNodeItemList (or null the returned value isn't compatible with that).

For example:

public object this[int index] {     get { return someOtherList[index]; } } 

Easiest thing to do is the step into it, though. That will tell you exactly where it is going.

like image 35
Marc Gravell Avatar answered Oct 10 '22 16:10

Marc Gravell