Indexers in C#

What are indexers?

Indexers in C# are special properties that allow accessing objects like arrays using square brackets. They simplify data retrieval and manipulation, making it easier to work with custom classes or collections in a user-friendly way.

Syntax of Indexer:

The syntax for defining an indexer is:

public returnType this[indexType index]
{
   get
   {
      // Getter logic
   }
   set
   {
      // Setter logic
   }
}
Use of Indexers:
  • Indexers in C# allow accessing elements or properties using square brackets, like arrays.
  • They simplify data retrieval and manipulation for custom classes or collections.
  • Indexers are useful for creating custom data structures with index-based access, improving code readability and providing a more user-friendly way to work with objects.
Implementation of Indexer

Here is source code of the C# Program to Implement Use of Indexers. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Implement Use of Indexers
 */
 
class values
{
    private int[] val = new int[10] { 10,20,30,40,50,60,70,80,90,100 }; 
    public int Length
    {
        get { return val.Length; }
    } 
    public int this[int index]
    {
        get
        {
            return val[index];
        }
 
        set
        {
            val[index] = value;
        }
    }
}
class MainClass
{
    static void Main()
    {
        values newval = new values();
        newval[3] = 58;
        newval[5] = 60;
        for (int i = 0; i < 10; i++)
        {
            System.Console.WriteLine("Element #{0} = {1}", i, newval[i]);
        }
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
 
    }
}
Program Explanation

1. The program defines a class named “values” with an array “val” containing 10 integer values from 10 to 100.
2. The class has a “Length” property that returns the length of the “val” array.
3. It also has an indexer, which allows getting and setting elements in the “val” array using square brackets.
4. The “MainClass” contains the “Main” method where we create an instance of the “values” class called “newval”.
5. We use the indexer to set the values 58 and 60 at index 3 and 5 of the “val” array in “newval“.
6. A “for” loop is used to display all elements in the “val” array along with their indices.
7. The program waits for any key press to exit after displaying the elements.

advertisement

Time Complexity: O(n)
The time complexity of the program is O(n) due to the “for” loop that iterates through the array.

Space Complexity: O(1)
The space complexity is O(1) as it uses a fixed-size array and no additional data structures, resulting in constant space usage.

Runtime Test Cases
 
Element #0 : 10
Element #1 : 20
Element #2 : 30
Element #3 : 58
Element #4 : 50
Element #5 : 60
Element #6 : 70
Element #7 : 80
Element #8 : 90
Element #9 : 100
Press any key to exit
Limitations of Indexers in C#
  • Only one indexer per class, named “this”.
  • Indexers cannot be static, they need an instance of the class.
  • Indexers cannot use “ref” or “out” parameters.
  • Indexers cannot be virtual or override.
  • Indexers cannot have different accessibility for getter and setter.
  • Indexers cannot use the “params” keyword in their parameters.

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

Free 30-Day C Certification Bootcamp is Live. Join Now!
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.