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";
}