Reputation: 9284
I am working on a project that constructs lambda expressions dynamically. In s specific scenario I've constructed dynamically an expression which equals to this one:
byte i = 1;
byte j = 1;
var firstConstant = Expression.Constant(i);
var secondConstant = Expression.Constant(j);
var lambda = Expression.Lambda(Expression.Add(firstConstant, secondConstant));
lambda.Compile().DynamicInvoke();
I Know that primitive types don't have operators overloading and the compiler actually cast the variables/constants to int before the addition and the result back to byte which i don't therefore the exception is being raised. My question is what is the logic to perform add operations without knowing the types and without loosing some data in case I need to handle float point types?
Upvotes: 3
Views: 2393
Reputation: 1500785
Basically I'd conditionally test the Type
of each operand to see whether it's byte
, sbyte
etc, and introduce an Expression.Convert
if necessary.
It's probably worth looking at what the C# compiler generates for:
Expression<Func<byte, byte, int>> expr = (a, b) => a + b;
... then try to get your own code to generate the right thing.
Upvotes: 3
Reputation: 70369
try
byte i = 1;
byte j = 1;
var firstConstant = Expression.Constant(i.GetType () == typeof (Byte) ? (int) i : i);
var secondConstant = Expression.Constant(j.GetType () == typeof (Byte) ? (int) j : j);
var lambda = Expression.Lambda(Expression.Add(firstConstant, secondConstant));
lambda.Compile().DynamicInvoke();
this way you don't loose anything if it is something other than a byte...
Also note that doing byte r = i + j;
gives you compile time error about "no automatic conversion from int to byte".
Upvotes: 1
Reputation: 473
That might not be possible. The Expression.Add does not perform overflow checking and it looks for the implementation of the Binary + operator. The other overload allows to specify the MethodInfo to select the method to perform the Add.
If you can ensure that all your types going in, support this method you can use the above logic. It does work for short because the binary + operator is defined. The same is not present for the System.Byte class and hence you have the problem. Even with the Compiler implementation, you cannot do:
byte i = 1;
byte j = 2;
byte sum = i+j; // Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
Upvotes: 0