![]() |
VOOZH | about |
In C#, Indexer allows an instance of a class or struct to be indexed as an array. When an indexer is defined for a class, then that class will behave like a virtual array. It can be overloaded. C# has multiple indexers in a single class. To overload an indexer, declare it with multiple parameters and each parameter should have a different data type. Indexers are overloaded by passing 2 different types of parameters. It is similar to method overloading.
Example 1: Overload the Indexer by int and float Data Types
Hello Geeks
Explanation: In the above example, int and float types are used to overload the indexer. The “Hello” word is assigned using the int indexer whereas the float parameter is used to give the value “Geeks” to the string.
Example 2: Overload Indexers by int and string data types and using get accessor (Read-Only).
This is C# Indexers Overloading.
Explanation: In the above example, we are using only the get accessor in an overloaded indexer that enables the read-only mode. This means we can not modify the given value. Int and string types are used to overload the indexer. Public string this[string flag] also enables read-only mode.
Note: The indexer overloading cannot be done by just changing the return type of the get block.