#365 – Overloading an Indexer
July 12, 2011 Leave a comment
You can define several versions of an indexer in a class, each indexed using a different type, overloading the indexer.
In the example below, we can index using the Days enumerated type or a 0-based integer representing the day.
public class Logger
{
private Dictionary<Days, LogMessage> dailyMessages = new Dictionary<Days, LogMessage>();
public LogMessage this[Days day]
{
get { return dailyMessages[day]; }
set { dailyMessages[day] = value; }
}
public LogMessage this[int i]
{
get { return dailyMessages[(Days)i]; }
set { dailyMessages[(Days)i] = value; }
}
}
Using this class, we could then index using either the Days or the integer type.
Logger log = new Logger();
log[Days.Mon] = new LogMessage("Monday was a good day");
log[2] = new LogMessage("Tuesday not bad either");
In this example, we indexed into the same internal data object. But we could have also indexed into different objects, depending on the indexer’s type.