I had an interview where I was asked the following:
Question: A method with same name and signature but different return type. Is it possible and what is this type c
Though return type covariance is not supported in C#, it is possible to emulate it by using explicit implementation and method hiding. That is a pattern which is used thoroughly in the ADO.NET APIs.
E.g.:
public interface ISomeValue { }
public abstract class SomeValueBase : ISomeValue { }
public class SomeValueImpl : SomeValueBase { }
public interface ISomeObject { ISomeValue GetValue(); }
public abstract class SomeObjectBase : ISomeObject
{
ISomeValue ISomeObject.GetValue() { return GetValue(); }
public SomeValueBase GetValue() { return GetValueImpl(); }
protected abstract SomeValueBase GetValueImpl();
}
public class SomeObjectImpl : SomeObjectBase
{
protected override SomeValueBase GetValueImpl() { return GetValue(); }
public new SomeValueImpl GetValue() { return null; }
}
By doing that, the net result of calling GetValue()
is that it will always match the most specific available type.