Bookmark and Share

Generics Don't Make Me Sad

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 two 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.

ol.AddRange(sl.ToArray());

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

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
Telerik Developer Evangelist, C# MVP

JustCode

Telerik .NET Ninja

 

INETA Community Speakers Program

 

MVP - Visual C#

 

Friend of RedGate

World Map

Tag cloud

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.