When this code is run (I'm using .NET 6.0), it recurses infinitely, and never gets to DoSomething()
in IInterface
, instead of returning the Class
instance from the interface.
It seems because of the return type of the method in the class being the same as in the interface, the compiler seems to think the interface's method is being reimplemented in the class, and the method calls itself.
If the method's return type is changed to the concrete class, it works without a problem. Why is it?
using System;
public class Program
{
public static void Main()
{
var obj = new Class();
var ret = obj.DoSomething();
Console.WriteLine("Finished");
}
}
interface IInterface {
IInterface DoSomething() {
return new Class();
}
}
class Class : IInterface {
// Infinite recursion
public IInterface DoSomething() => ((IInterface)this).DoSomething();
// Works
//public Class DoSomething() => (Class)((IInterface)this).DoSomething();
}