Open In App

C# | Indexers

Last Updated : 13 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Properties in C#

An indexer allows an instance of a class or struct to be indexed as an array. If the user will define an indexer for a class, then the class will behave like a virtual array. Array access operator i.e ([ ]) is used to access the instance of the class which uses an indexer. A user can retrieve or set the indexed value without pointing an instance or a type member. Indexers are almost similar to the Properties. The main difference between Indexers and Properties is that the accessors of the Indexers will take parameters.

Syntax:  

[access_modifier] [return_type] this [argument_list]
{
get
{
// get block code
}
set
{
// set block code
}
}

In the above syntax:

  • access_modifier: It can be public, private, protected or internal.
  • return_type: It can be any valid C# type.
  • this: It is the keyword which points to the object of the current class.
  • argument_list: This specifies the parameter list of the indexer.
  • get{ } and set { }: These are the accessors.

Example: 

C#




// C# program to illustrate the Indexer
using System;
 
// class declaration
class IndexerCreation
{
 
    // class members
    private string[] val = new string[3];
     
    // Indexer declaration
    // public - access modifier
    // string - the return type of the Indexer
      // this - is the keyword having a parameters list
    public string this[int index]
    {
 
        // get Accessor
        // retrieving the values
        // stored in val[] array
        // of strings
        get
        {
 
            return val[index];
        }
 
        // set Accessor
        // setting the value at
        // passed index of val
        set
        {
 
            // value keyword is used
            // to define the value
            // being assigned by the
            // set indexer.
            val[index] = value;
        }
    }
}
 
// Driver Class
class main {
     
    // Main Method
    public static void Main() {
         
        // creating an object of parent class which
        // acts as primary address for using Indexer
        IndexerCreation ic = new IndexerCreation();
 
        // Inserting values in ic[]
        // Here we are using the object
        // of class as an array
        ic[0] = "C";
        ic[1] = "CPP";
        ic[2] = "CSHARP";
 
        Console.Write("Printing values stored in objects used as arrays\n");
         
        // printing values
        Console.WriteLine("First value = {0}", ic[0]);
        Console.WriteLine("Second value = {0}", ic[1]);
        Console.WriteLine("Third value = {0}", ic[2]);
     
    }
}


Output:  

Printing values stored in objects used as arrays
First value = C
Second value = CPP
Third value = CSHARP


Implementing Indexers

  1. Multiple Index Parameters: Indexers can have multiple parameters, allowing for more complex indexing scenarios. You can define an indexer with multiple parameters to access elements based on different criteria.
  2. Indexer Overloading: Similar to methods, indexers can be overloaded in C#. This means you can define multiple indexers with different parameter types or counts, providing different ways to access elements in the class or struct.
  3. Read-Only Indexers: By omitting the set accessor in the indexer declaration, you can create read-only indexers. This restricts the ability to modify elements through the indexer, allowing only the retrieval of values.
  4. Implicit vs. Explicit Interface Implementation: Indexers can be implemented implicitly or explicitly when defined as part of an interface. Implicit implementation is used when the indexer is defined within the class itself, while explicit implementation is used when the indexer is implemented explicitly to resolve any naming conflicts.
  5. Indexers in Collections: Indexers are commonly used in collection classes, such as dictionaries, lists, and arrays. They provide a convenient way to access and manipulate elements within these collections based on an index or key.
  6. Indexers in Custom Classes: Indexers can be implemented in custom classes to provide customized access to class members based on an index. This allows for more intuitive and expressive interaction with instances of the class.

Here is an example demonstrating the previous indexer’s implementation:

C#




using System;
 
public class MyCollection
{
    private int[] data = new int[10];
 
    // Indexer with multiple parameters
    public int this[int index, bool square]
    {
        get
        {
            if (square)
                return data[index] * data[index];
            else
                return data[index];
        }
        set
        {
            if (square)
                data[index] = (int)Math.Sqrt(value);
            else
                data[index] = value;
        }
    }
 
    // Overloaded indexer with string parameter
    public int this[string name]
    {
        get
        {
            switch (name.ToLower())
            {
                case "first":
                    return data[0];
                case "last":
                    return data[data.Length - 1];
                default:
                    throw new ArgumentException("Invalid index parameter.");
            }
        }
    }
 
    // Read-only indexer
    public int this[int index]
    {
        get { return data[index]; }
    }
}
 
public class Program
{
    public static void Main()
    {
        MyCollection collection = new MyCollection();
 
        // Setting values using multiple parameter indexer
        collection[0, false] = 5;
        collection[1, false] = 10;
        collection[2, false] = 15;
        collection[3, false] = 20;
 
        // Getting values using multiple parameter indexer
        Console.WriteLine(collection[0, false]); 
        Console.WriteLine(collection[1, true]);  
 
        // Getting values using string parameter indexer
        Console.WriteLine(collection["first"]);  
        Console.WriteLine(collection["last"]);   
 
        // Getting values using read-only indexer
        Console.WriteLine(collection[2]);        
 
 
 
        Console.ReadLine();
    }
}


Output

5
100
5
0
15

Important Points About Indexers: 

  • There are two types of Indexers i.e. One Dimensional Indexer & MultiDimensional Indexersperforming the. The above discussed is One Dimensional Indexer.
  • Indexers can be overloaded.
  • These are different from Properties.
  • This enables the object to be indexed in a similar way to arrays.
  • A set accessor will always assign the value while the get accessor will return the value.
  • this” keyword is always used to declare an indexer.
  • To define the value being assigned by the set indexer, ” value” keyword is used.
  • Indexers are also known as the Smart Arrays or Parameterized Property in C#.
  • Indexer can’t be a static member as it is an instance member of the class. 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads