SoFunction
Updated on 2025-03-07

C# Getting Started with Indexer Example

This article shows how to use C# indexer, which is very necessary for beginners of C# to master. The specific usage is as follows:

First of all, the indexer is a new class member introduced by C#, which allows objects in the class to be referenced as conveniently and intuitively as arrays. An indexer is very similar to a property, but an indexer can have a parameter list and can only act on instance objects, not directly on a class. A class that defines an indexer allows you to access members of a class using the [ ] operator just like accessing an array. (Of course there are many advanced applications, such as mapping arrays through indexers, etc.)

The syntax of the indexer is as follows:

1、It can accept 1 or more parameters
2、Use this as the indexer's name
3、Parameterized member properties: contains set and get methods.

The format is as follows:
 
[Access Modifier] Data Type this [Data Type Identifier]
{
get{};
set{};
}

The example code is as follows:

public class Indexsy
  {
    private string[] array ;
    public Indexsy(int num)
    {
      array = new string[num];
      for (int i = 0; i < num; i++)
      {
        array[i] = "Array"+i;
      }
    }
 
    public string this[int num]
    {
      get { return array[num]; }
      set { array[num] = value; }
    }
  }
 
///Indexor call      Indexsy sy = new Indexsy(10);
      (sy[5]);//Output Array5

Examples of multi-parameters are as follows:

public class Indexsy
  {
    private string[] array ;
    public Indexsy(int num)
    {
      array = new string[num];
      for (int i = 0; i < num; i++)
      {
        array[i] = "Array"+i;
      }
    }
 
    public string this[int num, string con]
    {
      get {
        if (num == 6)
        {
          return con;
        }
        else
        {
          return array[num];
        }
      }
      set
      {
        if (num == 6)
        {
          array[num] = con;
        }
        else
        {
          array[num] = value;
        }
 
      }
    }
  }
 
//Method call      Indexsy sy = new Indexsy(10);
      sy[5,"10"] = "Replace set value"; 
      (sy[5,""]+" "+sy[6,"Replace internal parameters"]+" "+sy[8,""]);//The output is to replace the set value. Replace the internal parameters Array8,

Interested readers can debug the above code manually, which can deepen their understanding of how to use C# indexer and further consolidate the basic knowledge.