This is a common problem with generics, but I hope someone has found
the best way of solving it.
I have these classes: "Fruit" which is a baseclass, and "Apple" which
is derived. Further I have an "AppleBasket" which is a class that
contains a collection of apples. So, some code:
class Fruit{
}
class Apple : Fruit
{
}
abstract class FruitBasket
{
public void ListFruit()
{
foreach(Fruit fruit in Fruits)
Debug.WriteLine("Hello fruit : "+fruit);
}
abstract ICollection<Fruit> Fruits{ get; }
}
class AppleBasket : FruitBasket
{
// Don't want a <Fruit> collecion here.
private ICollection<Apple> apples;
public ICollection<Fruit> Fruits
{
get{ return apples; } // Can't do this!
}
}
The obvious way is to have a private collection of "Fruit" in the
applebasket, but if I'm doing loads of handling in the Applebasket that
is specific to apples, then I cant do that without casting each fruit
to apple all the time. Not something you want to do *only* because you
have to return the collection as a collection of fruit in one single
property. That would mean that generics really worked to make the code
uglier rather than better.
Also, I cant cast the ICollection<Apple> to ICollection<Fruit> since
they aren't inherited from eachother. Note that the 'AppleBasket' class
in this example isnt supposed to be though of as a collection class or
anything that itself should be generic, like Basket<Apple>, It's just
an unfortunate circumstance of the example...
So how to how to resolve this? any suggestions are welcome...
thanks