Indexer
Indexer
What is Indexer ??
• C# indexers are usually known as smart arrays.
• Indexers are implemented through get and set accessors for the [ ] operator.
• The value keyword is used to define the value being assigned by the set
indexer.
• There are two types of Indexers i.e. One Dimensional Indexer &
MultiDimensional Indexer. The above discussed is One Dimensional
Indexer.
• Syntax:
[access_modifier] [return_type] this [argument_list]
{
get { // get block code }
set { // set block code }
}
• access_modifier: It can be public, private, protected or
internal.
• return_type: It can be any valid C# type.
• this: It is the keyword which points to the object of the
current class.
• argument_list: This specifies the parameter list of the
indexer.
• get{ } and set { }: These are the accessors.
Example
public IndexedNames()
{
for (int i = 0; i < size; i++)
{
namelist[i] = "N. A.";
}
}
public string this[int index]
{
get {
string tmp;
if( index >= 0 && index <= size-1 )
{ tmp = namelist[index]; }
else { tmp = "";}
return ( tmp );}
set
{
if( index >= 0 && index <= size-1 )
{namelist[index] = value;}
}
}
public int this[string name]
{
get
{
int index = 0;
while(index < size)
{
if (namelist[index] == name)
{
return index;
}
index++;
}
return index;
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Komal";
names[1] = "Heena";
names[2] = "Kajal";
names[3] = "Pooja";
names[4] = "Roshani";
names[5] = "Meera";
names[6] = "Heer";