Simple understanding and usage of indexers in C #

Source: Internet
Author: User
An indexer is a special class member that allows objects to be accessed in an array-like manner, which makes the program look more intuitive and easier to write.

1, the definition of the indexer

Class members in C # can be any type, including arrays and collections. When a class contains arrays and collection members, the indexer greatly simplifies the access operations of an array or collection member.

You define indexers in a way that is similar to defining properties, in the following general form:

[modifier] Data type this[index type indexed]  {      get{//get property's code}                                                       set{//Set property's code}  }

Modifiers include Public,protected,private,internal,new,virtual,sealed,override, Abstract,extern.

The data type is the type that represents the array or collection element that will be accessed.

The indexer type indicates which type of index the indexer uses to access an array or collection element, which can be an integer, which can be a string, and this represents an array or collection member that operates on this object, which can simply be understood as the name of the indexer, so the indexer cannot have a user-defined name. For example:

Class Z  {          //full set of 100 integers          private long[] arr = new long[100];          Declare indexer public          Long This[int index]          {              get              {//Check index range                  if (Index < 0 | | Index >=)                  {                      return 0;                  }                  else                  {                      return arr[index];                  }              }              Set              {                  if (!) ( Index < 0 | | Index >=)                  {                      Arr[index] = value;}}     }

2. Use of indexers

You can access an array member of an instance of a class by means of an indexer, which is similar in general form to the following: Object name [index]

The data type of the index must be the same as the index type of the indexer. For example:

Z  z=new  z ();  z[0]=100;  z[1]=101;  Console.WriteLine (Z[0]);

Indicates that an object z is created first, and then the array elements in the object are referenced by an index.


The type of the indexer is not limited to integers in C #. For example, you can use strings for indexers. You can implement an indexer of this class by searching for a string within the collection and returning the corresponding value. Because accessors can be overloaded, strings and integer versions can coexist.

Class Daycollection  {        string[] days={"Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"};        private int GetDay (string testday)       {          int i=0;          foreach (String day)            {                if (day==testday)                        return i;                         i++;             }           return-1;        }         public int this[string Day]        {              Get{return (GetDay (Day)}}        }     static void Main (string[] args) c19/>{       daycollection week=new daycollection ();       Console.WriteLine ("Fri:{0}", week["Fri"]);       Console.WriteLine ("Abc:{0}", week["ABC"]);  }

Results: Fri:5

Abc:-1

3. Indexers in the interface

Indexers can also be declared in an interface, and there are two differences between an interface indexer and a class indexer:


The first is that the interface indexer does not use modifiers;

The second is that the interface indexer contains only accessors get or set, and there are no implementation statements.


The purpose of the accessor is to indicate whether the indexer is read-write, read-only, or write-only, and if it is read-write, the accessor get or set cannot be omitted at the same time, if it is read-only, the set accessor is omitted, and if it is write-only, the get accessor is omitted.

For example:

Public interface iaddress  {  string this[int index]{get;set;}  String Address{get;set;}  String Answer ();  }

Indicates that the declared interface Iaddress contains 3 members: an indexer, an attribute, and a method in which the indexer is readable and writable.

4. Comparison of indexers and attributes

Indexers and properties are members of a class and are syntactically very similar. Indexers are typically used in custom collection classes to manipulate collection objects by using indexers as easily as arrays, whereas properties can be used with any custom class, which enhances the flexibility of the class's field members.




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.