Using the C # indexer

Source: Internet
Author: User
Tags arrays

Indexers are syntactically convenient for you to create classes, structs, or interfaces that the client application can access as arrays. Indexers are often implemented in types that are primarily used to encapsulate internal collections or arrays. For example, suppose you have a class named TempRecord, which represents the degrees of Fahrenheit for 10 different time records within 24 hours. This class contains an array of float type named "Temps" that represents the temperature and a DateTime representing the date of the record temperature. By implementing an indexer in this class, the client can access the temperature in the TempRecord instance through floattemp=tr[4] instead of the floattemp=tr.temps[4] syntax. Indexer notation simplifies the syntax of the client application and enables other developers to understand the class and its purpose more intuitively.

To declare an indexer on a class or structure, use the This keyword, as shown in the following example:

Copy Code

public int This[int Index]    //Indexer declaration
{
Get and set accessors
}

Note

The indexer type and its parameter type must be at least as accessible as the indexer itself. For more information about accessibility levels, see access modifiers.

For more information about how to use indexers with interfaces, see interface indexers.

The signature of an indexer consists of the number and type of its formal parameters. It does not include an indexer type or a formal parameter name. If more than one indexer is declared in the same class, they must have a different signature.

The indexer value is not part of a variable; therefore, you cannot pass the indexer value as a ref or out parameter.

To provide an indexer with a name that can be used by another language, use the Name property in the declaration. For example:

Copy Code

[System.Runtime.CompilerServices.IndexerName ("Theitem")]
public int this [int index] //Indexer declaration
{
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.