0

In this SO question, we see how to create an indexer for a class. Is it possible to create a read-only indexer for a class?

Here is the Indexer example provided by Microsoft:

using System;

class SampleCollection<T>
{
   // Declare an array to store the data elements.
   private T[] arr = new T[100];

   // Define the indexer to allow client code to use [] notation.
   public T this[int i]
   {
      get { return arr[i]; }
      set { arr[i] = value; }
   }
}

class Program
{
   static void Main()
   {
      var stringCollection = new SampleCollection<string>();
      stringCollection[0] = "Hello, World";
      Console.WriteLine(stringCollection[0]);
   }
}
// The example displays the following output:
//       Hello, World.
lachy
  • 1,833
  • 3
  • 18
  • 27

1 Answers1

4

A read-only Indexer can be achieved by not including a set property in the declaration of the Indexer.

To modify the Microsoft example.

using System;

class ReadonlySampleCollection<T>
{
   // Declare an array to store the data elements.
   private T[] arr;

   // Constructor with variable length params.
   public ReadonlySampleCollection(params T[] arr) 
   {
       this.arr = arr;
   }

   // Define the indexer to allow client code to use [] notation.
   public T this[int i]
   {
      get { return arr[i]; }
   }
}

public class Program
{
   public static void Main()
   {
      var stringCollection = new ReadonlySampleCollection<string>("Hello, World");
      Console.WriteLine(stringCollection[0]);
      // stringCollection[0] = "Other world"; <<<< compiler error.
   }
}
// The example displays the following output:
//       Hello, World.
lachy
  • 1,833
  • 3
  • 18
  • 27