It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.
List<string> sl = new List<string>();
List<object> ol;
ol = sl;
results in Cannot implicitly convert type System.Collections.Generic.List<string>
to System.Collections.Generic.List<object>
And then...
List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;
results in Cannot convert type System.Collections.Generic.List<string>
to System.Collections.Generic.List<object>
Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.
I have a:
And I was going to fill it with data collected in an
List<object>
What finally worked for me was this one:.Cast
it to the type you want to get anIEnumerable
from that type, then typecast theIEnemuerable
to theList<>
you want.If you're using .NET 3.5 have a look at the Enumerable.Cast method. It's an extension method so you can call it directly on the List.
It's not exactly what you asked for but should do the trick.
Edit: As noted by Zooba, you can then call ol.ToList() to get a List
That's actually so that you don't try to put any odd "object" in your "ol" list variant (as
List<object>
would seem to allow) - because your code would crash then (because the list really isList<string>
and will only accept String type objects). That's why you can't cast your variable to a more general specification.On Java it's the other way around, you don't have generics, and instead everything is List of object at runtime, and you really can stuff any strange object in your supposedly-strictly typed List. Search for "Reified generics" to see a wider discussion of java's problem...
Mm, thanks to previous comments I found two ways to find it out. The first one is getting the string list of elements and then casting it to IEnumerable object list:
And the second one is avoiding the IEnumerable object type, just casting the string to object type and then using the function "toList()" in the same sentence:
I like more the second way. I hope this helps.
Such covariance on generics is not supported, but you can actually do this with arrays:
C# performs runtime checks to prevent you from putting, say, an
int
intoa
.