0
0
C Sharp (C#)programming~5 mins

Indexer declaration in C Sharp (C#)

Choose your learning style9 modes available
Introduction

An indexer lets you access objects like arrays using square brackets. It makes your class easier to use and feels natural.

You want to access elements inside a class using an index, like a list or array.
You have a collection inside your class and want to provide easy access to its items.
You want to hide the internal data structure but still allow users to get or set values by position.
You want to make your class behave like a container with simple syntax.
Syntax
C Sharp (C#)
public return_type this[type index] {
    get {
        // return value at index
    }
    set {
        // set value at index
    }
}

The keyword this is used to declare an indexer.

You can define get and set accessors to read and write values.

Examples
Simple indexer for a string array inside a class.
C Sharp (C#)
public string this[int index] {
    get { return array[index]; }
    set { array[index] = value; }
}
Indexer using a string key, like a dictionary.
C Sharp (C#)
public int this[string key] {
    get { return dictionary[key]; }
    set { dictionary[key] = value; }
}
Sample Program

This program shows how to use an indexer to get and set days of the week by index. It also handles invalid indexes gracefully.

C Sharp (C#)
using System;

class WeekDays {
    private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

    public string this[int index] {
        get {
            if (index < 0 || index >= days.Length) {
                return "Invalid index";
            }
            return days[index];
        }
        set {
            if (index >= 0 && index < days.Length) {
                days[index] = value;
            }
        }
    }
}

class Program {
    static void Main() {
        WeekDays week = new WeekDays();
        Console.WriteLine(week[1]);  // Access using indexer
        week[1] = "Monday";         // Set using indexer
        Console.WriteLine(week[1]);
        Console.WriteLine(week[10]); // Invalid index
    }
}
OutputSuccess
Important Notes

Indexers can have multiple parameters but usually have one.

You can make indexers read-only by only providing a get accessor.

Indexers improve code readability by allowing array-like access to objects.

Summary

Indexers let you use square brackets to access class data like arrays.

Use this keyword with parameters to declare an indexer.

Define get and set to control reading and writing.