Read-Only violation on List<T> in C#?

63 Views Asked by At

Is there any violation of the read only keyword when its used in combination with List ??

For example

class Program
{
    public List<string> InputList;
    public List<string> DefaultList;
    public readonly List<string> ReadOnlyList;

    public Program()
    {
        InputList = new List<string>() { "Initialized String" };
        DefaultList = InputList;
        ReadOnlyList = InputList;
    }

    static void Main(string[] args)
    {
        var p = new Program();
        p.SampleMethod();
        Console.ReadKey();
    }

    private void SampleMethod()
    {
        Console.WriteLine("inputList - " + InputList.LastOrDefault());
        Console.WriteLine("readOnlyList - " + ReadOnlyList.LastOrDefault());
        Console.WriteLine("defaultList - " + DefaultList.LastOrDefault());
        InputList.Add("Modified String");
        Console.WriteLine("inputList - " + InputList.LastOrDefault());
        Console.WriteLine("readOnlyList - " + ReadOnlyList.LastOrDefault());
        Console.WriteLine("defaultList - " + DefaultList.LastOrDefault());
    }
}

and the output thats printed

inputList - Initialized String

readOnlyList - Initialized String

defaultList - Initialized String

inputList - Modified String

readOnlyList - Modified String

defaultList - Modified String

Concept of readonly is, its value could be changed only inside the constructor,if its not been initialized.So in the above example, what is the exact difference between ReadOnlyList and DefaultList, when both the collection were changed at runtime.

And I find no difference by changing ReadOnlyList to IReadOnlyCollection as well.Can someone help me understanding this concept.

1

There are 1 best solutions below

0
iSpain17 On

As per the documentation:

In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class.

You are doing this exactly, assigning inside the constructor.

The List itself is readonly, not its content.