Hi all.
In this blog post I am going to whine a lot about the missing features of generics, that make the coders miserable.
Generally, there is one repeating case that's giving me the hard time: Passing generic-based collections.
Lets look at the following example:
class Circle : Shape { ... }
void foo (IEnumerable<Shape> shapes) { ... }
void bar ()
{
foo (new List<Circle>());
}
You get a compilation error for that one. I can't understand why. Logically, if a Circle is a Shape and a List is an IEnumerable, than a List of Circles is an Enumeration of Shapes! Why is it wrong?
Another example occure when using the 'where' clause:
class ShapesHandler<T> where T : Shape
{
void foo(params T[] shapes) { ... }
void bar ()
{
List<Shape> someShapes = new List<Shape>();
foo (someShapes.ToArray());
}
}
This also yields a compilation error. And of course the same goes if I had an array of Circles that I wanted to cast to an array of Shapes. The same error.
Again, I cannot understand why; If the class ShapesHandler specifically defines that it can take any class type that is a Shape, why can't I pass in an array of shapes where ever an array of T is needed, and why can't I cast an array of T to an array of Shapes?
(If you have a reasonable explanation, I would be glad to hear it. So far I only got the pretty lame explanation of 'this is a different type, this is how the compiler works' which is really unacceptable by me as it only describes the problem in a different words)
Itai.