Search code examples
c#methodscovariancevtable

Workaround for lack of return type covariance when overriding virtual methods


is there any way to 'hack' or 'coerce' covariant overrides in to C#?

For example:

public class Alpha {
    public virtual Alpha DoSomething() {
        return AlphaFactory.GetAlphaFromSomewhere();
    }
}
public class Beta : Alpha {
    public override Beta DoSomething() {
        return BetaFactory.GetBetaFromSomewhere();
    }
}

Unfortunately, C# doesn't support this (which seems a bit ridiculous, but that's neither here nor there).

I thought I might have an answer with method hiding:

new public Beta DoSomething() {
    return BetaFactory.GetBetaFromSomewhere();
}

But this doesn't add the entry in to the 'vtable', it just basically declares a brand new method with the same name, and as such means that accessing Betas through a pointer to an Alpha will call Alpha.DoSomething().

So, any good tricks?


Solution

  • You can do some pretty zany stuff with generics.

    public class Alpha<T> where T: Alpha<T> {
        public virtual T DoSomething() {
            throw new NotImplementedException();
        }
    }
    public class Beta : Alpha<Beta> {
        public override Beta DoSomething() {
            throw new NotImplementedException();
        }
    }