Search code examples
c#classtypesinterface

Specifying a type in an interface of the type that inherits this interface


Need a real implementation of this code

interface IExample{
   public this ReturnMe();
}
class Example : IExample {
   public this ReturnMe(){...} //returns an instance of the Example class
} 

Solution

  • You can return interface itself:

    interface IExample
    {
        public IExample ReturnMe();
    }
    class Example : IExample
    {
        public IExample ReturnMe() => new Example();
    } 
    

    Or use curiously recurring template pattern:

    interface IExample<T> where T : IExample<T>
    {
        public T ReturnMe();
    }
    
    class Example : IExample<Example>
    {
        public Example ReturnMe() => new Example();
    } 
    

    Note that this will not prevent somebody from writing class Example : IExample<SomeOtherClass>.

    Another option available since C# 9 is switching to abstract base class and using covariant return types:

    abstract class ExampleBase
    {
        public abstract ExampleBase ReturnMe();
    }
    class Example : ExampleBase
    {
        public override Example ReturnMe() => new Example();
    }