Indexers In C#.NET

The .NET Framework stack

The .NET Framework stack (Photo credit: Wikipedia)

Indexer In .NET  

Indexers provide a natural syntax for accessing elements in a class or struct that encapsulate a list or dictionary of values. Indexers are similar to properties, but are accessed via an index argument rather than a property name. The string class has an indexer that lets you access each of its char values via an int index:


string s = “hello”;

Console.WriteLine (s[0]); // ‘h’

Console.WriteLine (s[3]); // ‘l’ 

The syntax for using indexers is like that for using arrays when the index is an integer type. 

 

Implementing an indexer 

 

To write an indexer, define a property called this, specifying the arguments in square brackets. For instance: 

 

class Sentence

 

{

 

string[] words = “The quick brown fox”.Split();

 

public string this [int wordNum] // indexer

 

{

 

get { return words [wordNum]; }

 

set { words [wordNum] = value; }

 

}

 

}

 

Here’s how we could use this indexer: 

 

Sentence s = new Sentence(); 

 

Console.WriteLine (s[3]); // fox 

 

s[3] = “kangaroo”; 

 

Console.WriteLine (s[3]); // kangaroo

 

 A type may declare multiple indexers, each with parameters of different types. An

 

indexer can also take more than one parameter:

 

 public string this [int arg1, string arg2]

 

{

 

get { … } set { … }

 

}

 

 If you omit the set accessor, an indexer becomes read-only.

 

 CLR indexer implementation

 

 Indexers internally compile to methods called get_Item and set_Item, as follows:

 

 public string get_Item (int wordNum) {…}

 

 public void set_Item (int wordNum, string value) {…} 

 

The compiler chooses the name “Item” by default—you can actually change this by

 

decorating your indexer with the following attribute: 

[System.Runtime.CompilerServices.IndexerName (“Blah”)]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s