Indexer (programming)

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Monkbot (talk | contribs) at 14:40, 3 October 2019 (→‎top: Task 16: replaced (1×) / removed (0×) deprecated |dead-url= and |deadurl= with |url-status=;). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In object-oriented programming, an indexer allows instances of a particular class or struct to be indexed just like arrays.[1] It is a form of operator overloading.

Implementation

Indexers are implemented through the get and set accessors for the operator[]. They are similar to properties, but differ by not being static, and the fact that indexers' accessors take parameters. The get and set accessors are called as methods using the parameter list of the indexer declaration, but the set accessor still has the implicit value parameter.

Example

Here is a C# example of the usage of an indexer in a class: [2]

class OurFamily
{
private long[] familyMember = new long[7];
  public long this [int index]
  {
    // The get accessor
    get
    {
      return familyMember[index];
    }

    // The set accessor with 
    set
    {
      familyMember[index] = value;
    }
  }
}

See also

References

  1. ^ jagadish980 (2008-01-29). "C# - What is an indexer in C#". http://forums.sureshkumar.net/forum.php: Bulletin: SURESHKUMAR.NET FORUMS. Archived from the original on September 22, 2009. Retrieved 2011-08-01. {{cite web}}: External link in |location= (help)CS1 maint: numeric names: authors list (link)
  2. ^ "C# Interview Questions". http://www.dotnetfunda.com/: .net Funda. Retrieved 2011-08-01. {{cite web}}: External link in |location= (help)