|
If properties are 'virtual fields', indexers are more like 'virtual arrays' . They allow a class to emulate an array, where the elements of this array are actually dynamically generated by function calls. They allow a class to be used just like an array. On the inside of a class, you manage a collection of values any way you want. These objects could be a finite set of class members, another array, or some complex data structure. The following are the advantages of the Indexers.
- Regardless of the internal implementation of the class, its data can be obtained consistently through the use of indexers.
- Indexers aren't differentiated by name, and a class cannot declare two indexers with the same signature. However, this does not entail that a class is limited to just one indexer. Different indexers can have different types and numbers of indexing elements (these being equivalent to method parameters, except that each indexer must have at least one indexing element, and the 'ref' and 'out' modifiers cannot be used).
Example: Demonstrate Indexers

ClsIndexers10.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
class ClsIndexers10
{
private String [] arrString;
private int arrSize;
public ClsIndexers10( int sizeofArray) {
arrSize = sizeofArray;
arrString = new String [arrSize];
for ( int i=0;i<arrSize;i++){
arrString[i] = "No Value" ;
}
}
public string this [ int indexValue]
{
get {
return arrString[indexValue];
}
set {
arrString[indexValue] = value ;
}
}
public string [] this [ string data]
{
get {
for ( int i = 0; i < arrSize; i++)
{
if (arrString[i] == data)
{
arrString[i] = "Hi" ;
}
}
return arrString;
}
set
{
for ( int i = 0; i < arrSize; i++)
{
if (arrString[i] == data)
{
arrString[i] = "Hi" ;
}
}
}
}
}
}
Form10.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form10 : Form
{
static int arrSize = 10;
ClsIndexers10 obj = new ClsIndexers10 (arrSize);
public Form10()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
label1.Text = "" ;
obj[2] = "HHHI" ;
obj[5] = "Vikrant" ;
obj[9] = "Amit" ;
for ( int i = 0; i < arrSize; i++)
{
label1.Text = label1.Text + "Indexer at " + i + obj[i] + "\n" ;
}
}
private void button2_Click( object sender, EventArgs e)
{
label1.Text = "" ;
String [] arrString = obj[ "No Value" ];
for ( int i = 0; i < arrString.Length; i++)
{
label1.Text = label1.Text + "Indexer at " + i + obj[i] + "\n" ;
}
}
}
}
Output:
Click On: Indexer Implementation

Click On: Indexer – With String

|