Search code examples
c#covariance

How to use covariant return types in interfaces


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.


Solution

  • Covariant return types are currently only supported via inheritance (as of C#9).

    Interface method implementation covariance is currently proposed as a future enhancement.

    For now, you can use explicit implementations to work around the limitation:

    public class ClassA : Interface<int>
    {
        public ClassA Method() {...}
        Interface<int> Interface<int>.Method() => Method();
    }
    

    With this approach, you can call Method on an reference to ClassA to get a ClassA, and also ensure the interface contract is honoured.