views:

74

answers:

2

Consider the following where class "Circle" inherits from "Shape":

dim objListOfCircles as new List(of Circle)

DrawShapes(objListOfCirlces)


Private sub DrawShapes(byref objListOfShapes as List(of Shape))

for each objShape as Shape in objListOfShapes
  objShape.Draw()
next 

end sub

I can't get this to work. What is the explaination as to why this doesn't work?

A: 

You should include your error and which line gets it, but ...

You have to cast them manually. 3.5 doesn't automatically cast generics like that. How to handle this depends on your requirements.

http://reddevnews.com/Articles/2009/05/01/Generic-Covariance-and-Contravariance-in-C-40.aspx?Page=2

Even better: http://msdn.microsoft.com/en-us/library/dd799517.aspx

That article explains it. Get to the section about Generic Collections. The key words for your question are covariance and contravariance.

Not sure about VB, but in C#, you could do what I think would translate to DrawShapes(objListOfCirlces.Cast(of Shape)().ToList())

uosɐſ
Why the down-vote?
uosɐſ
Yeah, wtf? +1..
Mike Mooney
Man, a thoughtful reply with helpful links and a code sample and I get dinged with no explanation? That's really shitty.
uosɐſ
+3  A: 

This is called covariance. It seems obvious that a generic list of derived objects (circles) should be easily castable to a generic list of base objects (shapes), it's something that most people expect to just work, and are suprised when it doesn't.

However, if you've every done any reflection work with them, generics are not nearly as simple as they appear to be, which complicates the code for this. I'm sure there are also a lot of theorectical reasons, or even actual good reasons, why this hasn't been supported up through NET v3.5

But, support for covariance has been added to .NET 4.0: http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx

Until you upgrade to that, you'll have to do it the hard way (do a .ToArray() on the derived object list feed that into the constructor of the base object list, or something similar)

Mike Mooney
+1 for good sportsmanship
uosɐſ