Getting Started with C #-indexers

Source: Internet
Author: User

Getting Started with C #-indexers

  Indexers allow instances of a class or struct to be indexed in the same way as an array. Indexers are similar to properties, except that their accessors take parameters.

Indexer Overview
    • Indexers enable an object to be indexed in a similar way to an array.

    • The get accessor returns a value. The set accessor assigns a value.

    • The This keyword is used to define indexers.

    • The value keyword is used to define the values assigned by the set indexer.

    • Indexers do not have to be indexed by integer values, and you decide how to define a specific lookup mechanism.

    • Indexers can be overloaded.

    • Indexers can have multiple parameters, such as when accessing a two-dimensional array.

classSamplecollection<t>{    Privatet[] arr =Newt[ -];  PublicT This[inti] {Get        {            returnArr[i]; }        Set{Arr[i]=value; }    }}//This class shows how client code uses the indexerclassprogram{Static voidMain (string[] args) {samplecollection<string> StringCollection =Newsamplecollection<string>(); stringcollection[0] ="Hello, World"; System.Console.WriteLine (stringcollection[0]); }}

In the previous example, a generic class was defined and provided with a simple get and set accessor method (as a method of assigning and retrieving values).

comparison between attributes and indexers

Indexers are similar to properties. In addition to the differences shown in the following table, all rules defined for a property accessor apply to the indexer accessor as well.

Property Indexer
Allows methods to be called, as if they were public data members. Allows a method on an object to be called, as if the object were an array.
Access is available through a simple name. Access is available through the indexer.
The get accessor for the property has no parameters. The get accessor of the indexer has the same formal parameter list as the indexer.
The set accessor of a property contains an implicit value parameter. In addition to the value parameter, the indexer's set accessor has the same formal parameter list as the indexer.
Can be a static member or an instance member. Must be an instance member.
indexers in an interface

The accessors of the interface indexer differ from the accessors of the class indexer in the following ways:

    • Interface accessors do not use modifiers.

    • The interface accessor has no body.

Therefore, the purpose of the accessor is to indicate whether the indexer is read-write, read-only, or write-only.

//Interface Indexer Public Interfaceisomeinterface{//declaring indexers    int  This[intIndex] {        Get; Set; }}//Inheriting Interfacesclassindexerclass:isomeinterface{Private int[] arr =New int[ -];  Public int  This[intIndex//Indexer Declaration    {        Get        {            //Check Index limits            if(Index <0|| Index >= -)            {                return 0; }            Else            {                returnArr[index]; }        }        Set        {            if(! (Index <0|| Index >= -) ) {Arr[index]=value; }        }    }}classmainclass{Static voidMain () {indexerclass test=NewIndexerclass (); //Initializing indexes 2 and 5 through indexerstest[2] =4; test[5] = +;  for(inti =0; I <=Ten; i++) {System.Console.WriteLine ("Element #{0} = {1}", I, test[i]); }    }}

However, when a class implements more than one interface using the same indexer signature, a fully qualified name is required to avoid ambiguity. For example, if the Employee class implements two interfaces ICitizen and IEmployee, and the two interfaces have the same indexer signature, an explicit interface member implementation must be used. That is, the following indexer declares:

Implements the indexer on the IEmployee interface, and the following declaration:

Implements the indexer on the ICitizen interface.

Reliable Programming

There are two main ways to improve the security and reliability of indexers:

    • When you set and retrieve the value of any buffer or array accessed from the indexer, always ensure that your code performs scope and type checking.

    • You should set as many restrictions as possible for the accessibility of get and set accessors. This is especially important for set accessors.

Getting Started with C #-indexers

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.