jeudi 3 août 2017

C#: Find out result type of arithmetic operations in code (e.g. int + double = double)

I'm trying to come up with a function to determine the result type of arithmetic operations, say for the case of addition:

Type TypeOfAddition(Type leftType, Type rightType)
{
  // ???
}

Type TypeOfMultiplication(Type leftType, Type rightType)
{
  // ???
}

// ... same for subtraction and division

These desired result of these functions is probably clear; Essentially, my goal is do to the same (at runtime) that Visual Studio does when inferring types to "var"-type variables when doing arithmetic operations.

For example,

public class MyClass
{
    public double SomeProperty { get; set; } = 0;

    public static string operator +(MyClass left, double right)
    {
        // ...
    }
}

TypeOfAddition(typeof(int), typeof(double)); // Should return typeof(double)
TypeOfAddition(typeof(string), typeof(int)); // Should return typeof(string)
TypeOfAddition(typeof(MyClass), typeof(double));  // Should return typeof(string)

My base idea was an implementation like, conceptually

Type TypeOfAddition(Type leftType, Type rightType)
{
  return leftType.GetMethods().Single(x =>
    x.Name == "op_Addition" &&
    x.GetParamters().Count == 2 &&
    x.GetParameters().Last().ParameterType == rightType);
}

but

A) This won't work for base types like int, double etc., which don't seem to explicitly define operator overloads, and

B) The above linq clause won't catch all cases yet (e.g. inheritance)

I could hard-code the base types and try to come up with a smart solution for B) as well, but that seems relatively .. unelegant.

Is there any smarter / easier / good solution to solving this? Mind you, I only want to get the theoretical type of the result of such an operation, without actually executing an arithmetic operation explicitly.

Thanks!





Aucun commentaire:

Enregistrer un commentaire