Is there any (technical) reason why C # requires all type parameters to be declared with the names of their enclosing classes?
For example, I would like to declare this:
public class FruitCollection<TFruit> : FoodCollection<TFoodGroup>
where TFruit : IFood<TFoodGroup>
where TFoodGroup : IFoodGroup { }
public class AppleCollection : FruitCollection<Apple> { }
public class TomatoCollection : FruitCollection<Tomato> { }
TFruit
is IFood<TFoodGroup>
, therefore, TFoodGroup
should be determined if TFruit
provided, although I did not explicitly declare it.
Instead, I have to do this:
public class FruitCollection<TFoodGroup, TFruit> : FoodCollection<TFoodGroup>
where TFruit : IFood<TFoodGroup>
where TFoodGroup : IFoodGroup { }
public class AppleCollection : FruitCollection<FruitGroup, Apple> { }
public class TomatoCollection : FruitCollection<VegetableGroup, Tomato> { }
The second method works very well and prevents the compilation of any invalid combinations, but it gets confused as more and more unnecessary type declarations are added to the parameter list.
Other definitions in the set:
public interface IFoodGroup { }
public class FruitGroup : IFoodGroup { }
public class VegetableGroup : IFoodGroup { }
public interface IFood<TFoodGroup> where TFoodGroup : IFoodGroup { }
public class Apple : IFood<FruitGroup> { }
public class Tomato : IFood<VegetableGroup> { }
public abstract class FoodCollection<TFoodGroup> where TFoodGroup : IFoodGroup { }
source
share