Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, why can't a List<string> object be stored in a List<object> variable

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.

like image 765
Matt Sheppard Avatar asked Aug 09 '08 02:08

Matt Sheppard


2 Answers

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.

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

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

like image 42
Ray Avatar answered Sep 16 '22 15:09

Ray


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#?

like image 173
Mike Stone Avatar answered Sep 19 '22 15:09

Mike Stone