Hello Friends, In this tutorial you are going to learn Indexer in C#. An indexer is a way to indexed an object of a class or struct as an array.  You can access the item from an Indexer in the same way as in an array.

After Completing this tutorial you will be able to understand:

  • What is Indexer in C#?
  • How to use Indexer in C#?

Introduction:

An indexer is a special type of property in which we an object of a class or struct as an array. An indexer is similar to property expect that it defines with this keyword.

Key Point about Indexer:

  • An indexer is similar to Property expect it declared with this keyword.
  • It does not allow ref and out keyword.
  • We can override an Indexer using the different types of parameter.
  • An Indexer can be declared with any access modifiers like public, private, protected etc.
  • An Indexer should contain at least one parameter otherwise it will throw a compilation error.

The syntax for defining an Indexer:


public <return type> this[<parameter_type> index]

{

get{

//return value from the specified index

}

set{

// set values at the specified index

}

}

You can see in the above syntax we had declared an Indexer using this keyword.

Example:

Step 1- Open Visual Studio and Create a Console Application called IndexerDemo.

Step 2- Open Program.cs file and write the following code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IndexerDemo
{
public class LanguageCollection
{
private string[] arrLanguageCollection = new string[10]; // internal data storage
public string this[int iIndex]
{
get
{
if (iIndex < 0 && iIndex >= arrLanguageCollection.Length)
throw new IndexOutOfRangeException("Invalid Index");

return arrLanguageCollection[iIndex];
}

set
{
if (iIndex < 0 && iIndex >= arrLanguageCollection.Length)
throw new IndexOutOfRangeException("Invalid Index");

arrLanguageCollection[iIndex] = value;
}
}
}

public class Program
{
public static void Main(string[] args)
{
LanguageCollection objLanguageCollection = new LanguageCollection();
objLanguageCollection[0] = "C#";
objLanguageCollection[1] = "ASP.NET";
objLanguageCollection[2] = "ASP.NET MVC";
objLanguageCollection[3] = "SQL Server";
objLanguageCollection[4] = "PHP";
objLanguageCollection[5] = "Jquery";
for (int iCount = 0; iCount < 10; iCount++)
{
Console.WriteLine(objLanguageCollection[iCount]);

}
Console.ReadKey();

}
}
}

Output:

Indexer

Conclusion:

Hope you understand this tutorial. I will appreciate your Comments, Feedback and Suggestions.

View More:

Thank You.

 

Leave a Comment