Indexers in C#
Indexers in C#
Kushala Shrestha
Prajjwal Rana Magar
What is indexers?
Indexers in C# are special class members that allow
objects to be accessed using array-like syntax. They
enable the use of square brackets [] to retrieve or
assign values to an object, just like working with
arrays. By defining an indexer, a class can act as a
virtual array, simplifying data access and enhancing
code readability.
Syntax of Indexers
// Indexer definition
public string this[int index]
{
get
{
return elements[index]; // Getter to retrieve value at the specified index
}
set
{
elements[index] = value; // Setter to assign value at the specified index
}
}
}
class Program
{
static void Main()
{
// Create an instance of SampleCollection
SampleCollection collection = new SampleCollection();
// Assign values using the indexer
collection[0] = "Hello";
collection[1] = "World";
Limitations of Indexers
• Cannot be declared static.
• Only one indexer can exist per class with the same
signature.
• Limited to get and set operations.
Conclusion
Indexers in C# provide a powerful and intuitive
way to allow objects to be accessed like arrays,
enhancing both the flexibility and readability of
your code. They are particularly useful when
working with custom collections or data
structures, enabling developers to manage
internal data with array-like syntax.
Understanding how to effectively use indexers
allows you to write more efficient and
maintainable code while balancing their potential
drawbacks.
THANK
YOU