#362 – Defining an Indexer
July 7, 2011 1 Comment
An indexer is a class member that allows client code to index into an instance of class using an integer-based (0..n-1) index. The indexer allows an instance of a class to behave like an array.
Assume that we define a Logger class that stores a series of log messages in an internal collection:
public class Logger
{
private List<LogMessage> messages = new List<LogMessage>();
public void LogAMessage(LogMessage msg)
{
messages.Add(msg);
}
}
We define an indexer by defining a member that looks like a property, but uses the this keyword.
public LogMessage this[int i]
{
get
{
return messages[i];
}
}
The indexer allows us to write code that indexes into an instance of the class:
Logger log = new Logger();
log.LogAMessage(new LogMessage("This happened", 5));
log.LogAMessage(new LogMessage("Something else happened", -1));
LogMessage lm = log[1]; // returns 2nd element
Pingback: #366 – Defining an Indexer with More than One Parameter « 2,000 Things You Should Know About C#