Question

I just saw this in a c# project:

public char this[int index]

I consider myself new to C#; any one can help what it's meaning?

Was it helpful?

Solution

It is an Indexer.

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters. An indexer provides array-like syntax. It allows a type to be accessed the same way as an array. Properties such as indexers often access a backing store. We often accept a parameter of int type and access a backing store of array type.

Read it from http://www.dotnetperls.com/indexer

string s = "hello";
Console.WriteLine (s[0]); // 'h'
Console.WriteLine (s[3]); // 'l'

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 { ... }
}

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")]

OTHER TIPS

That's called an indexer. Read more about them at MSDN.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top