What is indexer in c#

In c# introduce new concept is Indexer. This is very useful for some situation. Let as discuss something about Indexer.
Indexer Concept is object act as an array.
Indexer an object to be indexed in the same way as an array.
Indexer modifier can be private, public, protected or internal.
The return type can be any valid C# types.
Indexers in C# must have at least one parameter. Else the compiler will generate a compilation error.

 this [Parameter]
 {
 get
 {
 // Write get code here
 }
 set
 {
 // Write set code here
 }
 }

For Example:

using System;
 using System.Collections.Generic;
 using System.Text;

namespace IndexersExample
 {
 class IndexerClass
 {
 private string[] range = new string[5];
 public string this[int indexrange]
 {
 get
 {
 return range[indexrange];
 }
 set
 {
 range[indexrange] = value;
 }
 }
 }
class Programe
 {
 public static void Main()
 {
 IndexerClass obj = new IndexerClass();

obj[0] = "Pawan";
 obj[1] = "Rohit";
 obj[2] = "Kamlakar";
 obj[3] = "Manoj";
 obj[4] = "Diwakar";
 Console.WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj[1], obj[2], obj[3], obj[4]);
 Console.ReadLine();
 }
 }
 }

Leave a Reply

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