Indexers

Posted by Techie Cocktail | 12:45 PM | | 0 comments »

Indexers look similar to properties having both get and set accessors in their implementation but they have fundamental differences.

Indexers enable to treat the objects as arrays. They allow instances of a class, struct or interface to be indexed like arrays. Unlike properties that have property names by which they are referenced, the indexers are denoted with this keyword with the compulsion of having one input parameter within the square bracket ([]) where this refers to the object instance.


public string this[int pos]
{
get
{
// return a value.
}
set
{
//set a value
}
}

The internal implementation of the indexers is hidden to its users. The object being used could be a finite set of class members, another array or a complex data structure.

The below example will give you a clear idea of its use and implementation.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace indexers
{
class Indexer
{
private string[] strArray;

public Indexer(int size)
{
strArray = new string[size];

for (int i = 0; i < size - 1; i++)
{
strArray[i] = "initialize";
}
}

public string this[int pos]
{
get
{
return strArray[pos];
}
set
{
strArray[pos] = value;
}
}
}

class Program
{
static void Main(string[] args)
{
int size = 10;
Indexer objIndexer = new Indexer(size);

objIndexer[3] = "Value Filled";

for (int i = 0; i <= size-1 ; i++)
{
Console.WriteLine(objIndexer[i]);
}
Console.Read();
}
}
}

In the above example, in the Indexer class’s constructor, the strArray is initialized to a default value. In the main() method of the program class, the Indexer class (having an indexer) is treated like an array and updates the encapsulated strArray.

Indexers can further be overloaded. You can have overloaded indexers for the same class by defining different signatures. The indexer signatures can be different by the number of parameters or types. During the call, the class will pickup the appropriate indexer based on the number and types of the parameters in the indexer call.

0 comments