Home »
.Net
Indexers in C#
In this article, we are going to learn about the indexers in C#, how to implement indexer in C#?
Submitted by IncludeHelp, on August 11, 2018
An Indexer is a special feature of C# to use an object as an array. If you define an indexer in a class then it will behave like a virtual array. Indexer is also known as smart array in C#. It is not a compulsory or essential part of OOPS.
It is also known as indexed property. It is a class property that allows to access data members using a feature of array.
We use this object to implement indexer in class.
Syntax:
<Modifier> <return type> this[parameter list]
{
get
{
//write code here
}
set
{
//write code here
}
}
Example
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Names
{
static public int len=10;
private string []names = new string[len] ;
public Names()
{
for (int loop = 0; loop < len; loop++)
names[loop] = "N/A";
}
public string this[int ind]
{
get
{
string str;
if (ind >= 0 && ind <= len - 1)
str = names[ind];
else
str = "...";
return str;
}
set
{
if (ind >= 0 && ind <= len - 1)
names[ind]=value;
}
}
}
class Program
{
static void Main()
{
Names names = new Names();
names[0] = "Duggu";
names[1] = "Shaurya";
names[2] = "Akshit";
names[3] = "Shivika";
names[4] = "Veer";
for (int loop = 0; loop < Names.len; loop++)
{
Console.WriteLine(names[loop]);
}
}
}
}
Output
Duggu
Shaurya
Akshit
Shivika
Veer
N/A
N/A
N/A
N/A
N/A
Important point regarding indexers:
- We use this keyword to implement indexer.
- Indexer can be overloaded.
- Indexer cannot be static.
Read more: Indexer overloading in C#