C#C
C#2y ago
Evyr

Is it possible to change the return type of interface method to the type of the implementing struct?

Say I have the following code:
interface IBiggerThan
{
    public abstract IBiggerThan GetBiggest(IBiggerThan compareTo);
}
struct A : IBiggerThan
{
    float _a;
    public A GetBiggest(A compareTo)
    {
        if (this._a > compareTo._a)
            return this;
        return compareTo;
    }
}
struct B : IBiggerThan
{
    float _b;
    public B GetBiggest(B compareTo)
    {
        if (this._b > compareTo._b)
            return this;
        return compareTo;
    }
}


I want to have GetBiggest return an instance of the struct its implemented within. This code obviously won't compile, but I'm wondering if there's a way to implement the intent behind it. I want to avoid returning object or IBiggerThan and then casting it wherever this method gets called, instead I want the return type to explicitly be that of the implementing struct. Is this possible, or am I missing something important?
Was this page helpful?