c# implement interface method with parameter of subclass type
c#, class-hierarchy
Solution
Make your interface generic
interface IClass<T> where T : IClass<T>
{
string print(T item);
}
class MyClass : IClass<MyClass>
{
public string print(MyClass item)
{
return item.ToString();
}
}
Problem
I have this desired class hierarchy: ``` interface IClass { string print(IClass item); } class MyClass : IClass { // invalid interface implementation // parameter type should be IClass not MyClass string print(MyClass item) { return item.ToString(); } } ``` I tried to solve interface implementation problem by using generic types as next with no success: ``` interface IClass { string print<T>(T item) where T : IClass; } class MyClass : IClass { string print<T>(T item) where T : MyClass { return item.ToString(); } } ``` What should I do?