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.
using System;
namespace HelloGeeksApp {
class HelloGeeks {
private string [] word = new string [2];
public string this [ int flag]
{
get
{
string temp = word[flag];
return temp;
}
set
{
word[flag] = value;
}
}
public string this [ float flag]
{
get
{
string temp = word[1];
return temp;
}
set
{
word[1] = value;
}
}
static void Main( string [] args)
{
HelloGeeks Obj = new HelloGeeks();
Obj[0] = "Hello" ;
Obj[1.0f] = " Geeks" ;
Console.WriteLine(Obj[0] + Obj[1.0f]);
}
}
}
|
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.
using System;
namespace Geeks {
class G4G {
private string [] str = new string [2];
public string this [ int flag]
{
get
{
string temp = str[flag];
return temp;
}
set
{
str[flag] = value;
}
}
public string this [ string flag]
{
get
{
return " C# Indexers Overloading." ;
}
}
static void Main( string [] args)
{
G4G Obj = new G4G();
Obj[0] = "This is" ;
Console.WriteLine(Obj[0] + Obj[ "GFG" ]);
}
}
}
|
Output:
This is C# Indexers Overloading.
Note: The indexer overloading cannot be done by just changing the return type of the get block.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 Jan, 2019
Like Article
Save Article