Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there isn't a ReadOnlyList<T> class in the System.Collections library of C#?

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.

like image 881
Baltasarq Avatar asked Sep 30 '10 15:09

Baltasarq


People also ask

What is the use of ReadOnlyCollection in C#?

An instance of the ReadOnlyCollection<T> generic class is always read-only. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.

Is a readonly collection mutable?

The fact that ReadOnlyCollection is immutable means that the collection cannot be modified, i.e. no objects can be added or removed from the collection.

What is ReadOnlyCollection?

ReadOnlyCollection makes an array or List read-only. With this type from System. Collections. ObjectModel, we provide a collection of elements that cannot be changed.


1 Answers

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().

like image 96
Reed Copsey Avatar answered Sep 20 '22 17:09

Reed Copsey