-1

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.

Dhivya Sadasivam
  • 155
  • 2
  • 2
  • 14
  • 1
    You're misunderstanding what the `readonly` keyword does – Jamiec Feb 27 '19 at 13:38
  • 2
    `readonly` applies to the reference, not the contents of the list. – lesscode Feb 27 '19 at 13:39
  • "Concept of readonly is, its value could be changed only inside the constructor" Depends on what you mean by "value". You´re right, that you cannot **re-reference** the variable. However you can of course call any member on that instance, e.g. `Add`. – MakePeaceGreatAgain Feb 27 '19 at 13:39

1 Answers1

0

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.

iSpain17
  • 2,502
  • 3
  • 17
  • 26