#362 – Defining an Indexer

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
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #362 – Defining an Indexer

  1. Pingback: #366 – Defining an Indexer with More than One Parameter « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: