Search code examples
c#interfaceoperations

IOperable interface .net


Is there some interface like this in .Net

public interface IOperable<T>
{

    T Add(T add);
    T Substract(T subs);
    T Multiply(T mult);
    T Divide(T div);
    //and so on
}

For manage generics that you know will be operable? Or even primitives.

For example for a class Interval<T> we will be able to get the Lenght if End and Start will be IOperable (End.Substract(Start);).

I know ISet<T> operations, but that approach is for non continuous cualitative elements, but for continuous elements i didn't see any approach in c#.

If not, why not exists in current .Net? Developing reasons? Philosophical? Are there any library that offers this approach?


Solution

  • "Nope".

    If it ever happens, it almost certainly won't be via an interface, but: via generic operator constraint support.

    There are some semantic issues with an interface: not all number systems implement all the same operators - and the results aren't always the same (division and multiplication of vectors / matrices, for example; or: you can add and subtract two TimeSpans, but you can't multiply or divide them, etc); and even when they do: the meaning can change (integer division is not the same as floating point division, and subtraction and negation get weird for unsigned data types, for example).

    Generic operator constraints are something that have been discussed a few times, but have never made it into the language.

    You can cheat with dynamic, but that involves "boxing", so has some non-trivial overhead. Or there are (or were) some generic operator services built into MiscUtil.