#363 – An Indexer Can Have Both get and set Accessors

Similar to a property, an indexer in C# can have either a get accessor for reading an element, a set accessor for writing an element, or both.

  • get accessor – read-only behavior
  • set accessor – write-only behavior
  • get and set accessors – read-write behavior

Here’s an example of a read-write accessor.

    public class Logger
    {
        private List<LogMessage> messages = new List<LogMessage>();

        // Read-write indexer
        public LogMessage this[int i]
        {
            get { return messages[i]; }
            set { messages[i] = value; }
        }

        public void LogAMessage(LogMessage msg)
        {
            messages.Add(msg);
        }
    }

We can then use the indexer to read and write elements in the internal list.

            Logger log = new Logger();

            log.LogAMessage(new LogMessage("This happened", 5));
            log.LogAMessage(new LogMessage("Something else happened", -1));

            LogMessage lm = log[1];   // Get 2nd element
            log[0] = new LogMessage("New 1st guy", 1);  // Replace 1st element
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: