Quote of the day: A Big Fat Lie - Time Heals All Wounds.

Tuesday, May 26, 2009

Indexers in C#

Indexers

Indexers are also called as smart Arrays in C#. Indexer allows your class to be used like an array. An indexer allows you to use an index on an object to obtain values stored within the object. In other words, it enables you to treat an object like an array and access that object using [ ] array access operator.

Defining an indexer is same as defining properties. Like properties, you use get and set when defining and indexer. Properties are defined using property name but with indexers, instead of creating a name, you use this keyword.

The format for defining an indexer is

this [argument list]
{
get
{
// Get code goes here
}
set
{
// Set code goes here
}
}



Indexer modifier can be private, public, protected or internal. The return type can be any valid C# types. The ‘this’ is a special keyword in C# to indicate the instance of the current class. Indexers in C# must have at least one parameter. Other wise the compiler will generate a compilation error.

Example of Indexer:



using System;
using System.Collections.Specialized;
namespace IndexerExample
{
class PhoneBook
{
ListDictionary nameDictionary = new ListDictionary();
public String this[string name]
{
get
{
return nameDictionary[name].ToString();
}
set
{
nameDictionary.Add(name,value);
}
}
}
class program
{
public static void Main()
{
PhoneBook phoneBook = new PhoneBook();
phoneBook["Joe"] = "111-111-1111";
phoneBook["Jessica"] = "222-222-2222";
phoneBook["John"] = "333-333-3333";
phoneBook["Jade"] = "444-444-4444 ";
phoneBook["Jevon"] = "555-555-5555";

Console.WriteLine("Indexer Example\n\n");
Console.WriteLine("{0}\n{1}\n{2}\n{3}\n{4}\n", phoneBook["Joe"], phoneBook["Jessica"], phoneBook["John"], phoneBook["Jade"], phoneBook["Jevon"]);
Console.WriteLine("\n");
Console.ReadLine();
}
}
}

1 comment: