I have the following class which implements an interface:
public class Category : IHierarchical<Category> {
...
}
I then have an inherited type called ProductCategory:
public class ProductCategory : Category {
...
}
Here's my IHierachical interface:
public interface IHierarchical<out T> where T : IHierarchical<T> {
T Parent { get; }
IEnumerable<T> Children { get; }
}
Finally I have the following extension method:
public static string MyExtension<T>(this T item) where T : IHierarchical<T> {
...
}
If I have an instance of type Category I can successfully call my extension method. However if my instance is of type ProductCategory I cannot call the extension method against it and instead I get the error:
The type 'ProductCategory' cannot be used as type parameter 'T' in the generic
type or method 'IHierarchicalExtensions.MyExtension<T>(T, string)'. There is no
implicit reference conversion from 'ProductCategory' to
'IHierarchical<ProductCategory>'.
I thought by making IHierachical covariant it would solve this issue. I'd appreciate it if someone could show me how this can be done. Thanks
ProductCategoryisIHierarchical<Category>which does not meet the restrainwhere T : IHierarchical<T>.ProductCategory is IHierarchical<Category>with inheritanc.