In the following simplified example, I need to abstract Collection classes in such a way that PrintFruitsAndEaters(oranges, orangeEaters); or PrintFruitsAndEaters(apples, appleEaters);
becomes possible:
abstract class Fruit
abstract class FruitEater
class Apple : Fruit
class AppleEater : FruitEater
class Orange : Fruit
class OrangeEater : FruitEater
class AppleCollection : List<Apple>
class OrangeCollection : List<Orange>
class AppleEaterCollection : List<AppleEater>
class OrangeEaterCollection : List<OrangeEater>
I’ve tried templatizing the method and collection classes, but i need to access methods specific to Fruit and FruitEater classes:
class FruitCollection<T> : List<T>
class FruitEaterCollection<T> : List<T>
void PrintFruitsAndEaters<T, S>(FruitCollection<T> fruits, FruitEaterCollection<S> eaters)
Then you want this:
This will constrain the
TandStypes as you require; calling the method with aFruitCollection<T>, where theTcannot be guaranteed to beFruitor a subtype, will result in a compile-time error. Same withSandFruitEater.Because of the constraint, when working with a value of type
Tyou will be able to access members of theFruitclass, and when working with a value of typeSyou will be able to access members of theFruitEaterclass.Note that, as per Brian’s (deleted) answer, you might want to add constraints to the collection types too:
But this will still not allow you to omit the constraints on the method.
(Also, inheriting
List<T>is an evil thing to do, instead useIList<T>)