'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 1:[1]

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 type:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1