Generics Don't Make Me Sad

by KodefuGuru 15. September 2008 18:15

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.

Tags: , ,

Kodefu

Comments

9/16/2008 8:56:52 AM #

Matt Sheppard

Cheers,

I can't remember if I was aware of either ConvertAll or the AddRange trick back at the time - I'm a fairly sure I just wrote my own loop and moved on. Both look like much nicer solutions than anything I came up with.

Clearly Eiffel just spoilt me early on Smile

Matt Sheppard Australia

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen

Whois KodefuGuru

Chris Eargle

Chris Eargle
.NET Community Champion

LinkedIn Twitter Technorati Facebook

MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er


World Map

RecentComments

Comment RSS

Tag cloud

Disclaimer

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

© Copyright 2010