In this article, we will find out about the indexers in C#, how to actualize indexer in C#?
An Indexer is an exceptional element of C# to utilize an article as a cluster. In the event that you characterize an indexer in a class, at that point it will carry on like a virtual cluster. The indexer is otherwise called shrewd cluster in C#. It’s anything but a mandatory or basic piece of OOPS.
It is otherwise called listed property. It is a class property that permits to get to information individuals utilizing an element of the exhibit.
We utilize this item to execute 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] = "Durgesh";
names[1] = "Kishan";
names[2] = "Aakash";
names[3] = "Vivek";
names[4] = "Vibhav";
for (int loop = 0; loop < Names.len; loop++)
{
Console.WriteLine(names[loop]);
}
}
}
}
Output
Durgesh
Kishan
Aakash
Vivek
Vibhav
N/A
N/A
N/A
N/A
N/A
The significant point with respect to indexers:
- We utilize this catchphrase to actualize indexer.
- The indexer can be over-burden.
- Indexer can’t be static.