C# | Overloading of Indexers
Prerequisite: Indexers in C#
Like functions, Indexers can also be overloaded. In C#, we can have 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 quite similar to method overloading.
Example 1: In the below program int and float types are used to overload the indexer. Here, “Hello” word is assigned using the int indexer whereas the float parameter is used to give the value “Geeks” to the string.
// C# Program to illustrate // the overloading of indexers using System; namespace HelloGeeksApp { class HelloGeeks { // private array of // strings with size 2 private string [] word = new string [2]; // this indexer gets executed // when Obj[0]gets executed public string this [ int flag] { // using get accessor get { string temp = word[flag]; return temp; } // using set accessor set { word[flag] = value; } } // this is an Overloaded indexer // which will execute when // Obj[1.0f] gets executed public string this [ float flag] { // using get accessor get { string temp = word[1]; return temp; } // using set accessor set { // it will set value of // the private string // assigned in main word[1] = value; } } // Main Method static void Main( string [] args) { HelloGeeks Obj = new HelloGeeks(); Obj[0] = "Hello" ; // Value of word[0] Obj[1.0f] = " Geeks" ; // Value of word[1] Console.WriteLine(Obj[0] + Obj[1.0f]); } } } |
Hello Geeks
Example 2: In the below program, we are using only get accessor in overloaded indexer which enables the read-only mode. Means we can’t modify the given value. Here int and string types are used to overload the indexer. public string this[string flag] contain only get accessor which enables the read-only mode.
// C# program to illustrate the concept // of indexer overloading by taking // only get accessor in overloaded indexer using System; namespace Geeks { class G4G { // private array of // strings with size 2 private string [] str = new string [2]; // this indexer gets called // when Obj[0] gets executed public string this [ int flag] { // using get accessor get { string temp = str[flag]; return temp; } // using set accessor set { str[flag] = value; } } // this indexer gets called // when Obj["GFG"] gets executed public string this [ string flag] { // using get accessor get { return " C# Indexers Overloading." ; // read only mode } } // Driver Code static void Main( string [] args) { G4G Obj = new G4G(); Obj[0] = "This is" ; // Value of str[0] Console.WriteLine(Obj[0] + Obj[ "GFG" ]); } } } |
This is C# Indexers Overloading.
Note: The indexer overloading cannot be done by just changing the return type of the get block.
Please Login to comment...