I want to use Expression.Add to sum two data types, which might be a double and an int (or any other mismatched pair), like this:
var pLeft = Expression.Parameter(typeof(int), "left");
var pRight = Expression.Parameter(typeof(double), "right");
var addition = Expression.Add(pLeft, pRight);
var lambda = Expression.Lambda<Func<int, double, double>>(addition, pLeft, pRight).Compile();
var res = method(1, 0.5);
However, I am promptly informed that:
The binary operator Add is not defined for the types 'System.Int32' and 'System.Double'.
It’s clear that the + operator isn’t defined for every possible pair of numbers, but that some sort of implicit conversion goes on when I write something like var x = 1 + 0.5. Is there a way to emulate this conversion using an expression, or otherwise a way to sum such types using an expression?
Use
Expression.Convertto convert one of the parameters to the type of the opposite one.Expression trees do not have an “opinion” on how implicit conversions should work because they are not language specific. C# has different rules for implicit conversions than VB.NET for example. Expression trees take a neutral stance and require explicit conversions.
For example, a performance oriented language might decide to implicitly convert the double to int because it prefers performance by default. C# prefers precision in this case. Expression trees can’t decide this problem generally.