Is there any way in C# to enforce operator overloading in derived classes?

Bit of a hack, but...

You could provide operator overloads in your base class that then call some published abstract methods in one of the classes to do the job there.

public abstract class MyClass
{
    public static MyClass operator +(MyClass c1, MyClass c2) 
    {
        return c1.__DoAddition(c2);
    }

    protected abstract MyClass __DoAddition(MyClass c2);
}

No. The only sensible way to do this would be to have a unit test check use reflection to find all concrete implementations, and then verify this condition. You could also perhaps do something at runtime re the same via a static constructor, but then the question is which static constructor?

Another approach is to drop the operators and use an interface-based approach; for example , if you need T to have +(T,T) then instead of operators have an interface with an Add(T) method. Another advantage here is that interfaces are usable from generics (typically via constraints), where-as using operators from generic code takes some effort.


You could implement the overloading in an abstract base class, but delegate the actually operation specifics to an abstract method. Then this will have to be implemented and the overloading will be don with their implementation.

public abstract class OverLoadingBase
{
    public abstract OverLoadingBase DoAdd(OverLoadingBase y);

    public static OverLoadingBase operator +(OverLoadingBase x, OverLoadingBase y)
    {
        return x.DoAdd(y);
    }    
}

Though I'm not sure if this is complete.