What does β€œthis [0]” mean in C #?

I looked through some library code and saw a method like:

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

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

+60
c #
May 20 '13 at 13:05
source share
4 answers

Find the indexer in the class.

C # allows you to define indexers to allow this kind 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 :

Index is a member that allows objects to be indexed just like an array. An indexer is declared as a property, except that it is the name of the element, followed by a list of parameters written between the delimiters [and]. Parameters are available in the indexer accessories (s). Like properties, indexers can be read and written, read-only and write-only, and indexer accessors (and) can be virtual.

A complete and complete definition can be found in section 10.9 of the Indexers specification.

+97
May 20 '13 at 1:07
source share

This means that the declaration type (or base class) has an β€œindexer” that supposedly takes int (or similar) and returns ... something (maybe an object ?). The code calls the get accessor indexer, passing 0 as an index - and then treats the return value as CollapsingRecordNodeItemList (or null return value is incompatible with this).

For example:

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

The easiest way to do this is step into it. This will tell you exactly where it is going.

+11
May 20 '13 at 1:07
source share

Assuming the class itself is inherited from some form, if IList / IList<T> , it simply returns (and distinguishes) 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 } 
+3
May 20 '13 at 1:07
source share

This means calling the item property get method in this class. He called the Indexer class

Indexers allow you to index instances of a class or structure as arrays. Indexers resemble properties, except that their accessors accept parameters.

+1
May 20 '13 at 1:07
source share



All Articles