I know that in .NET all arrays derive from System.Array and that the System.Array class implements IList
, ICollection
and IEnumerable
. Actual array types also implement IList<T>
, ICollection<T>
and IEnumerable<T>
.
This means that if you have, for example, a String[]
, then that String[]
object is also a System.Collections.IList
and a System.Collections.Generic.IList<String>
;.
It's not hard to see why those IList's would be considered "ReadOnly", but surprisingly...
String[] array = new String[0];
Console.WriteLine(((IList<String>)array).IsReadOnly); // True
Console.WriteLine(((IList)array).IsReadOnly); // False!
In both cases, attempts to remove items via the Remove()
and RemoveAt()
methods results in a NotSupportedException. This would suggest that both expressions correspond to ReadOnly lists, but IList's ReadOnly
property does not return the expected value.
How come?
Add
onIList
even though apparently is not read-only, throws a Not Supported exception ofCollection was of a fixed size
– HawkenIList.ReadOnly
is arguably correct in saying the array is not read only, because you can modify its elements (which, according to the documentation onReadOnly
, you are not supposed to be able to do) but of course this runs counter to how people actually useReadOnly
(to see if you can add or remove elements), so whenList<T>
rolled around they "fixed" it. – BertrandoArray
's implementation didn't get downvoted to hell. Seems like it was on the right track. – HawkenIList<T>
was instantiating aReadOnlyCollection<T>
, which was wrong and misleading. – Tagmemic