I would like to understand if it is possible to use covariant return types in interfaces in C#.
I have an interface like the one in the following code snippet and two classes which implement the interface. I would like to constraint the classes to implement the method Method
but I need it to return an object of type corresponding to the concrete classes.
The following code snippet shows what i would like to obtain.
public interface Interface<T>
{
public Interface<T> Method();
}
public class ClassA : Interface<int>
{
public ClassA Method() {...}
}
public class ClassB : Interface<string>
{
public ClassB Method() {...}
}
I’ve read online about covariance in return types in interfaces in C# but i’ve not found any solution for my problem, yet. I have also read some similar questions which propose some workarounds but they don’t fit for my case: i need to use Method
and then being able to call the other methods of ClassA or ClassB on the returned object without the need of a cast.
Is it allowed in C#? How could i solve my problem?
Thank you in advance.
user25452962 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.