Introduction
Indexer is similar to a property, which
is allows an object to be indexed like an array. If you define an
indexer for a class, then this class behaves like a virtual array, and
you can access the object of this class using the array operator.
Indexer are not defined with names, but you can use this keyword, which
refers to the object instance . Show in Example.
Example
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
use_indexer_in_c_sharp
{
class
use_Index
// create class
{
private
string[] List =
new
string[size];
//define member
static
public
int size = 8;
public use_Index()
//create constructor
{
for (int
a = 0; a < size; a++)
// provide
value of list
List[a] = "Not
Available";
}
public
string
this[int
index]
// define index property
{
get
{
string var;
if (index >= 0
&& index <= size - 1)
{
var = List[index];
}
else
{
var = "";
}
return (var);
}
set
{
if (index >= 0
&& index <= size - 1)
{
List[index] =
value;
}
}
}
static
void Main(string[]
args)
{
use_Index Name =
new
use_Index();
// create object of class
Name[0] = "Nitin";
Name[1] = "Arvind";
Name[2] = "Arshad";
Name[3] = "deepak";
Console.WriteLine("List
of Name:");
for (int
b = 0; b <use_Index.size;
b++)
{
Console.WriteLine(Name[b]);
//show value of List
}
Console.ReadKey();
}
}
}
Output: