-1

In the below code, Even though the collection is declared as readonly, we are able to add items into the collection. But it is a known fact like readonly modifier will allow initialization of the value either at declaration,initialization expression or in the constructor. How the below is possible? How readonly modifier behaves on different types?

class Program
{
    static void Main(string[] args)
    {
        ReadonlyStringHolder stringHolder = new ReadonlyStringHolder();
        stringHolder.Item = "Say Hello";//compile time error-Read only field cannot be initialized to

        ReadOnlyCollectionHolder collectionHolder = new ReadOnlyCollectionHolder();
        collectionHolder.ItemList.Add("A");
        collectionHolder.ItemList.Add("B");//No Error -How Is possible for modifying readonly collection

        Console.ReadKey();
    }
}

public class ReadOnlyCollectionHolder
{
    public readonly IList<String> ItemList = new List<String>();
}
public class ReadonlyStringHolder
{
    public readonly String Item = "Hello";
}
amesh
  • 1,311
  • 3
  • 21
  • 51

2 Answers2

2

Use ReadOnlyCollection instead.

readonly doesn't allow just to change the instance (except in the constructor)

public class ReadOnlyCollectionHolder
{
    private List<string> _innerCollection=new List<string>();

    public ReadOnlyCollectionHolder()
    {
        ItemList = new ReadOnlyCollection<String> (_innerCollection);
    }

    public readonly ReadOnlyCollection<String> ItemList {get;private set;}
}
Artiom
  • 7,694
  • 3
  • 38
  • 45
  • 1
    Basically, `readonly` changes the mutability of the variable itself (limiting it to just constructor can set the value) not the mutability of the backing object. – Anthony Dec 18 '13 at 14:24
  • @Anthony I got it clear..Thanks – amesh Dec 18 '13 at 14:27
1

You can't change the ItemList instance but you can call its methods. If you really want a readonly list you should consider using IReadOnlyList<T> or ReadOnlyCollection<T>

meziantou
  • 20,589
  • 7
  • 64
  • 83