A typed array implements both the System.Collections.IList
and System.Collections.Generic.ICollection<T>
interfaces, which both have their own IsReadOnly
properties. But what on earth is going on here?
var array = new int[10];
Console.WriteLine(array.IsReadOnly); // prints "False"
var list = (System.Collections.IList)array;
Console.WriteLine(list.IsReadOnly); // prints "False"
var collection = (System.Collections.Generic.ICollection<int>)array;
Console.WriteLine(collection.IsReadOnly); // prints "True"
The IList
view of the array behaves as I'd expect, returning the same as the array itself, however the ICollection<T>
view of the array returns true.
Is there any rational explanation for this behaviour, or is it a compiler/CLR bug? (I'd be really surprised if it's the latter as you'd imagine this would have been found before now, but it's so counter-intuitive I can't think what the explanation could be...).
I'm using C#3.0/.NET 3.5 SP1.
See Question&Answers more detail:os