#366 – Defining an Indexer with More than One Parameter

An indexer will typically have a single parameter, often based on an integer type.

        public LogMessage this[int i]
        {
            get { return messages[i]; }
            set { messages[i] = value; }
        }

You can also define an indexer that takes more than one parameter.  In the example below, we have an internal data structure that stores a list of messages for each day of the week.  We can retrieve a specific message by passing in a parameter representing the day, as well as a 0-based index into the list of messages for that day.

            // Get 1st Saturday message
            LogMessage msg = log[Days.Sat, 0];

Here’s what the definition of the indexer looks like.

        private Dictionary<Days, List<LogMessage>> dailyMessages = new Dictionary<Days, List<LogMessage>>();

        public LogMessage this[Days day, int i]
        {
            get { return dailyMessages[day][i]; }
        }
Advertisements