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?
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: Link
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)