Search code examples
c#numbersdelegatesoperators

Directly Derive Delegate for Double Division


The double numerical type has a division operator. I can divide one double by another by simply writing x / y where x and y are both doubles.

My understanding is that, in the computer, this operation uses a function called double.op_Divison, which takes two doubles as input and returns one double as output.

I want to directly create a delegate from that function. The following does not work, it throws a compiler error:

System.Func<double, double, double> d = double.op_Division;

I can always just create a new function acting as a intermediary:

System.Func<double, double, double> d = (double x, double y) => x / y;

But this is longer and more ugly. Additionally, I worry about its performance in situations requiring high efficiency.

Is there any way to directly create a delegate from the division operator without requiring an intermediary?


Solution

  • I don't believe you can directly use those hidden methods to construct delegate.

    One obvious option is to find the method via reflection and create the corresponding delegate:

    var methodInfo = typeof(System.Single).GetMethods(
           BindingFlags.NonPublic | BindingFlags.Static)
         .First(x=>x.Name.Contains("op_Division"));
    Func<Single, Single, Single> f = (Func<Single, Single, Single>)Delegate.CreateDelegate(
         typeof(Func<Single, Single, Single>),
         null, 
         methodInfo  
    );
    Console.WriteLine(f(1f, 2f));
    

    Note that the "op_Division" will have a different full name depending on the framework's version - latest once have it on IDivisionOperators interface rather than the class directly (may need to adjust BindingFlags too).

    Note on the problem: it is likely that either using numeric interfaces or expression trees would lead to more performant solution - makes sure to try all if performance is a concern as delegates will add overhead no matter how you construct them.