#365 – Overloading an Indexer

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.

Advertisements

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

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: