C# Feature – Indexers
Overview
Section titled “Overview”Indexers let instances be indexed like arrays, e.g., obj[key]
.
Introduced In
Section titled “Introduced In”C# 1 (2002)
Before
Section titled “Before”public string GetByKey(string key) { /* ... */ }
public string this[string key] { get => Lookup(key); set => Store(key, value); }
Annotated Example
Section titled “Annotated Example”public class DictLike{ private readonly Dictionary<string,string> _m = new(); public string this[string k] { get => _m[k]; set => _m[k] = value; }}
Gotchas & Best Practices
Section titled “Gotchas & Best Practices”- Use clear argument names/types; document behaviors for missing keys.
Related Features
Section titled “Related Features”Version Notes
Section titled “Version Notes”- Works with spans/index/range (C# 8+) on indexer types.