Practical Implementation of Indexer in C#

By | April 23, 2018

Before studying this article, there is one pre-requisite you should do. You should learn Properties in C#.

What is Indexer in C# ?

Indexer is an extended version of Properties in C#. It is an array of properties.

Things to remember before using Indexer

  1. Remove all the private variables within class and take a single variable which act as property.
  2. There is no name for Indexer unlike properties in C#.
  3. Indexer is referred by “this”.

Program for Indexer in C#

using System;

class Candidate
{
object[] data = new object[2];
public object this[int i]
{
get{ return data[i];}
set{data[i] = value;}
}
}
class Hr
{
public static void Main()
{
Candidate shubham = new
Candidate();
shubham[0] = “B.Tech”;
shubham[1] = 23;
Console.WriteLine(“Qualification of shubham is “+shubham[0]);
Console.WriteLine(“Age of shubham is “+shubham[1]);
}
}

Output:

Qualification of shubham is B.Tech

Age of shubham is 23

Leave a Reply

Your email address will not be published. Required fields are marked *