9️⃣ C# Advanced Concepts
Estimated reading: 3 minutes 26 views

πŸš€ C# Indexers – Enable Array-Like Access to Custom Objects


🧲 Introduction – Why Use Indexers in C#?

Sometimes you want your object to behave like an array or collectionβ€”allowing access to its internal elements using square brackets. Indexers in C# let you do exactly that. They allow objects to be indexed like arrays, improving usability, abstraction, and code readability.

🎯 In this guide, you’ll learn:

  • What indexers are and how they work
  • How to define and use indexers in C#
  • Real-world use cases and syntax patterns
  • Best practices and tips for implementation

πŸ” Core Concept – What Is an Indexer?

An indexer allows an object of a class or struct to be accessed using an index, similar to an array. It is defined using the this keyword and square brackets [].


πŸ”£ Basic Syntax of an Indexer

class Sample
{
    private string[] names = new string[3];

    public string this[int index]
    {
        get => names[index];
        set => names[index] = value;
    }
}

πŸ“˜ this[int index] allows the object to be indexed like sample[0].


πŸ’» Code Example – Using an Indexer

Sample s = new Sample();
s[0] = "Alice";
s[1] = "Bob";

Console.WriteLine(s[0]); // Output: Alice

🧡 Explanation:

  • s[0] = "Alice"; calls the indexer’s set
  • Console.WriteLine(s[0]); calls the indexer’s get

🧩 Indexer with Multiple Parameters

class Matrix
{
    private int[,] data = new int[3, 3];

    public int this[int row, int col]
    {
        get => data[row, col];
        set => data[row, col] = value;
    }
}

πŸ“˜ Access like:

Matrix m = new Matrix();
m[0, 1] = 5;
Console.WriteLine(m[0, 1]); // Output: 5

🧠 Indexer vs Property

FeaturePropertyIndexer
Access Patternobj.PropertyNameobj[index]
Use CaseNamed data memberIndexed collection-like access
Supports Multiple Params❌ Typically noβœ… Yes

πŸ› οΈ Real-World Use Cases

  • πŸ“¦ Custom collections (e.g., MyList<T>)
  • πŸ—‚οΈ Representing matrix or grid data
  • 🧾 Wrappers over Dictionary<TKey, TValue>
  • πŸ§ͺ Table row/column mappings
  • πŸ“‹ Form field access via keys

πŸ’‘ Best Practices & Tips

πŸ’‘ Tip: Validate the index to avoid IndexOutOfRangeException.

⚠️ Pitfall: Don’t use indexers for actions with side effectsβ€”it should only access or modify internal data.

πŸ“˜ Best Practice: Combine indexers with internal collections like arrays or lists.


πŸ“Œ Summary – Recap & Next Steps

🧡 Key Takeaways:

  • Indexers allow custom objects to be indexed like arrays.
  • Use this[index] to define readable and writable access.
  • Support multiple parameters for 2D structures.

βš™οΈ Real-world relevance: Widely used in custom data containers, matrix structures, and collection wrappers in C#.


❓ FAQ Section

❓ Can a class have more than one indexer?
βœ… No. A class can only have one indexer, but it can be overloaded with different parameter types.


❓ Can indexers be overloaded?
βœ… Yes. You can define multiple indexers with different parameter types or counts.


❓ Can I use string as an index?
βœ… Yes. Indexers support any type as an index:

public string this[string key] { get; set; }

❓ Do indexers support access modifiers?
βœ… Yes. You can define separate access levels for get and set.


❓ Are indexers the same as arrays?
βœ… No. Indexers just mimic array syntax but are custom-defined. Arrays are built-in types.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸš€ C# Indexers

Or Copy Link

CONTENTS
Scroll to Top