List<string> sl = new List</string><string>();
List<object> ol = new List</object><object>();
ol = sl;
Bzzzt…
Cannot implicitly convert type ‘System.Collections.Generic.List<string>’ to ‘System.Collections.Generic.List<object>’
Hmmm, well, I don’t see why not, but how about…
List<string> sl = new List</string><string>();
List<object> ol = new List</object><object>();
ol = (List<object>)sl;
Double bzzzt…
Cannot convert type ‘System.Collections.Generic.List<string>’ to ‘System.Collections.Generic.List<object>’
Seriously?
Am I missing something, or is this really so broken that, in spite of a string being an object, a List<string> can’t be converted to a List<object> without pulling everything out of one type before putting it back into the other?
January 17th, 2007 at 12:30 am
This is actually quite a common problem
This explains why:
http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx
January 18th, 2007 at 10:01 pm
Thanks Victor, that certainly does confirm what I thought
To be honest, I’d rather live with the possibility of runtime type errors, though it sounds like they may consider making them covariant at some later stage. At the very least it would be nice to have a clean way to perform an explicit conversion rather than having to manually loop through…
Ah well, I guess I’ll just have to live with the idea that nothing’s ever going to quite live up to Eiffel.
September 16th, 2008 at 5:47 am
Here’s the easiest way to do it, and it doesn’t require looping.
ol.AddRange(sl.ToArray());