What are indexers in C#? explain with example in details way.
IT-Hardware & Networking
Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
In C#, indexers allow an object to be accessed like an array by using square brackets (
[]). They provide a way to define how values are retrieved or assigned using an index.Why Use Indexers?
Without an indexer:
Usage:
With an indexer, the syntax becomes much cleaner.
Basic Indexer Syntax
Usage:
Output:
How It Works
The keyword
thisdefines an indexer:getis executed when reading a value.setis executed when assigning a value.valuerepresents the assigned value inside the setter.Example:
Internally calls:
Indexers with Multiple Parameters
Indexers can accept multiple parameters.
Usage:
Output:
String-Based Indexers
Indexers don't have to use integers.
Usage:
Output:
Read-Only Indexer
If you only need retrieval:
Usage:
Output:
Write-Only Indexer
Although uncommon, you can create a write-only indexer:
Real-World Examples
Indexers are commonly used in:
Examples in .NET:
List<T>Dictionary<TKey, TValue>DataRowList<T>uses an indexer internally.Indexer vs Property
obj.Nameobj[0]thiskeywordExample:
vs
Interview Question
Can a class have multiple indexers?
Yes, as long as their parameter signatures are different.
Usage:
Output:
Summary
An indexer is a special class member that lets objects be accessed using array-like syntax (
obj[index]). It is declared using thethiskeyword and can haveget,set, or both accessors. Indexers are particularly useful when building custom collections or data structures that should feel natural to use, similar to arrays, lists, and dictionaries.