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?
Basically I’d conditionally test the
Typeof each operand to see whether it’sbyte,sbyteetc, and introduce anExpression.Convertif necessary.It’s probably worth looking at what the C# compiler generates for:
… then try to get your own code to generate the right thing.