In C#, why can’t a List object be stored in a List variable

Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string!

As a side note, I think it would be more significant whether or not you can do the reverse cast:

List<object> ol = new List<object>();
List<string> sl;
sl = (List<string>)ol;

I haven’t used C# in a while, so I don’t know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects.

Does anybody know or can test if such a cast is legal in C#?

Leave a Comment