Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

“Strange” C# property syntax

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?

like image 423
user522745 Avatar asked Jan 03 '13 11:01

user522745


2 Answers

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")]
like image 93
Soner Gönül Avatar answered Oct 14 '22 00:10

Soner Gönül


this is called indexer.

  • Indexer
  • C++ implementation of the C# Property and Indexer with Accessor-Modifiers
like image 32
John Woo Avatar answered Oct 14 '22 00:10

John Woo