views:

64

answers:

1

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 ReadOnlyListBase. This is a base class for containers of objects that let their positions be accessed but not modified. Even there is an example in the Microsoft msdn.

http://msdn.microsoft.com/en-us/library/system.collections.readonlycollectionbase.aspx

I slightly modified the example in msdn 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.

+7  A: 

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
Thank you, that's what I was looking for.
Baltasarq