Geeks With Blogs
Path Notes of a Kodefu Master blog

I came across an interesting blog post today entitled, "C# generics make me sad..." by Matt Sheppard.

Matt has an issue with generic Lists, in that you can't easily convert from one to another even if one constraint is inherited from the other constraint.

List<String> sl = new List<String>();
List<Object> ol = new List<Object>();
ol = sl;

This will throw the error "Cannot implicitly convert type ‘System.Collections.Generic.List<string>’ to ‘System.Collections.Generic.List<object>’ ."

Matt then tries to cast sl to List<Object>. This fails too, as List<String> and List<Object> are too different classes. String may inherit from Object, but List<String> does not inherit from List<Object>.

One responder provided a link that goes into detail of why this doesn't work. However, the point of this post is to provide a simple solution to Matt's main gripe that "it would be nice to have a clean way to perform an explicit conversion rather than having to manually loop through..."

List<T> does have a method called ConvertAll, although you have to pass in a delegate. It makes for messy looking code, but it is the correct way to solve this problem.

ol = sl.ConvertAll<Object>(new Converter<String, Object>(delegate(String s)
      return s;

There is another way to do this with other methods on List<T>. The methods aren't necessarily meant to convert one list to another but result in less mess.


I would let either block pass a code review barring other cirumstances.

Posted on Monday, September 15, 2008 7:22 PM Kodefu | Back to top

Comments on this post: Generics Don't Make Me Sad

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Chris Eargle | Powered by: