What does "this[0]" mean in 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?


Solution 1:

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.

Solution 2:

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.

Solution 3:

Assuming the class itself inherits from some form if IList/IList<T>, it's just returning (and casting) the first element in the collection.

public class BarCollection : System.Collections.CollectionBase
{
    public Bar FirstItem
    {
        get { return this[0] as Bar; }
    }

    #region Coming From CollectionBase
    public Object this[ int index ]  {
        get { return this.InnerList[index]; }
        set { this.InnerList[index] = value; }
    }
    #endregion
}