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

Indexer with custom types in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Indexers let you access objects like arrays using custom keys. Using custom types as keys makes your code clearer and more organized.

You want to access elements in a collection using a special key type, not just numbers.
You have a class that stores data identified by a custom object, like a coordinate or a name.
You want to make your class easier to use by allowing bracket [] access with your own key type.
Syntax
C Sharp (C#)
public ReturnType this[CustomKeyType key] {
    get { /* return value for key */ }
    set { /* set value for key */ }
}

The keyword this defines the indexer.

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

Examples
Indexer using a custom Coordinate type as key.
C Sharp (C#)
public string this[Coordinate coord] {
    get { return data[coord]; }
    set { data[coord] = value; }
}
Indexer using a Person object as key to store ages.
C Sharp (C#)
public int this[Person person] {
    get { return ages[person]; }
    set { ages[person] = value; }
}
Sample Program

This program creates a Grid class with an indexer that uses a Coordinate record as the key. It stores and retrieves strings at specific coordinates.

C Sharp (C#)
using System;
using System.Collections.Generic;

public record Coordinate(int X, int Y);

public class Grid {
    private Dictionary<Coordinate, string> data = new();

    public string this[Coordinate coord] {
        get => data.ContainsKey(coord) ? data[coord] : "Empty";
        set => data[coord] = value;
    }
}

class Program {
    static void Main() {
        var grid = new Grid();
        grid[new Coordinate(0, 0)] = "Start";
        grid[new Coordinate(1, 2)] = "Tree";

        Console.WriteLine(grid[new Coordinate(0, 0)]);
        Console.WriteLine(grid[new Coordinate(1, 2)]);
        Console.WriteLine(grid[new Coordinate(2, 2)]); // no value set
    }
}
OutputSuccess
Important Notes

Make sure your custom key type implements equality correctly (like a record) so dictionary lookups work.

Indexers make your class feel like a collection with easy access syntax.

Summary

Indexers let you use bracket [] access on your classes.

You can use any custom type as the key for an indexer.

Implement get and set to control how values are accessed and stored.