Internal code can really change it.
IsReadOnly indicates that the list cannot be directly modified through this interface.
I agree that "code that expects IList with IsReadOnly true to never change is inherently broken."
Microsoft has implemented the ImmutableList<T> class, and perhaps this is one of the reasons.
IReadOnlyList to the rescue? Er, unfortunately not:
List<int> test = new List<int> {1}; IReadOnlyList<int> readOnly = test;
For these reasons, that some time ago I suggested not declaring interfaces for immutable types .
And here is another example using List<T>.AsReadOnly() . This demonstrates that you can mutate the list using IReadOnly set true using only the built-in .Net types:
Console.WriteLine(shouldBeReadOnly.IsReadOnly); // Readonly? Yep! This prints True. Console.WriteLine(shouldBeReadOnly[0]); // Prints 1. Console.WriteLine(shouldBeReadOnly.Count); // Prints 1. test[0] = 2; test.Add(-1); Console.WriteLine(shouldBeReadOnly[0]); // Prints 2. Oops. It wasn't readonly at all. Console.WriteLine(shouldBeReadOnly.Count); // Prints 2.
Please note that you can change the number of elements as well as the elements themselves.
Matthew watson
source share