1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - About Value Types and Reference Types

By , About.com Guide

10 of 10

Using an Indexer - Indexed Properties

Continuing with the playing cards example, this demonstrates the use of an indexer. This is a way of accessing the Cards via an indexed property. Within the class Deck, cards is an array but in the Main function, I access each card by using MyCards[ i ], yet MyCards is the actual instance of Deck. This property declaration is what does the trick.
public CardType this[ int index] {
         get { return cards[ index ]; }
         set { cards[ index ]= value; }
  }
The property member is defined thus
this[ int index ]
and is called an indexer, in this case it's an int called index. Each class or struct can have multiple indexers as long as the signatures are unique. The signature is the bit inside square brackets eg [int index]. You might for example want to find the position of a card in the deck and there is a second indexer provided with this signature
this [string value]
This calls a function FindIndex() to search the array for a matching short card, e.g. "2D". This only works if the ShortCard bool is set to true. If it is, then a card can be retrieved like this:
CardType C = MyCards["2D"];
Unlike other properties, this one always uses the keyword this (ie it refers to an instance of this class- this means it only works with instance objects and NOT static classes. The syntax is very similar to properties with get and set, but includes an indexed field. The general form is shown below, where the indexed field is called arr.
public T this[int i]
{
    get { return arr[ i ]; }
    set { arr[ i ] = value; }
}
Just like a property this includes get and set accessor methods to alter or access the private field array or structure. But you must use this for accessing the indexer.

That completes this tutorial. The next one will be on WinForms.

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Using an Indexer - Indexed Properties

©2009 About.com, a part of The New York Times Company.

All rights reserved.