36

Reading about the problem of creating a read only primitive vector in C# (basically, you cannot do that),

public readonly int[] Vector = new int[]{ 1, 2, 3, 4, 5 }; // You can still changes values

I learnt about ReadOnlyCollectionBase. This is a base class for containers of objects that let their positions be accessed but not modified. Even there is an example in Microsoft Docs.

ReadOnlyCollectionBase Class - Microsoft Docs

I slightly modified the example to use any type:

public class ReadOnlyList<T> : ReadOnlyCollectionBase {
    public ReadOnlyList(IList sourceList)  {
      InnerList.AddRange( sourceList );
    }

    public T this[int index]  {
      get  {
         return( (T) InnerList[ index ] );
      }
    }

    public int IndexOf(T value)  {
      return( InnerList.IndexOf( value ) );
    }



    public bool Contains(T value)  {
      return( InnerList.Contains( value ) );
    }

}

... and it works. My question is, why does not exist this class in the standard library of C#, probably in System.Collections.Generic? Am I missing it? Where is it? Thank you.

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
Baltasarq
  • 12,014
  • 3
  • 38
  • 57

1 Answers1

44

There is ReadOnlyCollection<T>, which is the generic version of the above.

You can create one from a List<T> directly by calling list.AsReadOnly().

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • This is not a true `ReadOnlyList` - in the sense that you are guaranteed that the contents of the `ReadOnlyList` will never change - since `ReadOnlyCollection` only wraps the original list, and modifying the original list will modify the collection. – M Kloster Sep 13 '19 at 14:24
  • @M Kloster, but at a memory level that is true of any collection. Marking a collection as readonly is really only a suggestion to developers using the code that modifying it could result in unwanted behavior. Of course, if the collection refers to something not found in memory, then actually forcing a change would be impossible. – Rhaokiel Feb 19 '20 at 17:45