#364 – Defining an Indexer whose Parameter Is an Enumerated Type

You typically define an indexer that is indexed using an integer parameter.  When you define an indexer, the parameter used as the index can actually be of any type.

Below is an example of using an enumerated type as the index.

Suppose you want a class that stores a log message for each day of the week.  We might want to use the class like this:

            Logger log = new Logger();

            log[Days.Mon] = new LogMessage("Monday was a good day");
            log[Days.Fri] = new LogMessage("Everyone went home");

            LogMessage msg = log[Days.Mon];  // Retrieve Monday message

We define an indexer that takes a parameter whose type is the enumerated Days type.

    public class Logger
    {
        // Internal collection
        private Dictionary<Days, LogMessage> dailyMessages = new Dictionary<Days, LogMessage>();

        // Indexer
        public LogMessage this[Days day]
        {
            get { return dailyMessages[day]; }
            set { dailyMessages[day] = value; }
        }
    }

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

Leave a comment