About
In this code snippet, we will learn how to implement indexers in C#.
Indexers allow classes to be indexed just like arrays. To retrieve or set a value you just provide an index inside a set of square brackets just like you would for an array.
Let’s see how to implement and use indexers in the code snippet below.
Code:
using System;
namespace Indexer
{
class Program
{
static void Main(string[] args)
{
int[] intArr = new int[5] { 5,2,3,8,7 };
MyClass MC = new MyClass(intArr);
//Get element at the third index.
Console.WriteLine(MC[3]);
//Set the value using an indexer.
MC[3] = 20;
//Lets check the value again.
Console.WriteLine(MC[3]);
Console.ReadLine();
}
}
class MyClass
{
public int[] IntArray { get; set; }
public MyClass(int[] intArray)
{
IntArray = intArray;
}
//Indexer is defined with the "this" keyword.
public int this[int index]
{
get
{
return this.IntArray[index];
}
set
{
this.IntArray[index] = value;
}
}
}
}





