The reason this code works is due to the fact that the Enumerator
cannot modify the collection:
var roList = new List<string>() { "One", "Two", "Three" };
IEnumerable<object> objEnum = roList;
If we try to do the same thing with a List<object>
, instead of IEnumerable<object>
, we would get a compiler error telling us that we cannot implicitly convert type List<string>
to List<object>
. Alright, that one makes sense and it was a good decision by Microsoft, in my opinion, as a lesson learned from arrays.
However, what I can't figure out is why in the world is this hardline rule applicable to something like ReadOnlyCollection
? We won't be able to modify the elements in the ReadOnlyCollection
, so what is the safety concern that caused Microsoft to prevent us from using covariance with something that's read-only? Is there a possible way of modifying that type of collection that Microsoft was trying to account for, such as through pointers?