#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