Generic arithmetic operations using the dynamic keyword in C# .NET

When I was writing the expression evaluator, I ran into the problem of handling all the different ways of performing arithmetic operations between integers, floating point numbers and strings. It would be entirely unmanageable to write for all the cases. It would make far more sense if I could just do something like this

Pseudocode

void PerformOperation(val1, val2)
{
    return val1 + val2;
}

Using the dynamic keyword, I was able to come up with a solution. The idea is to mix generic types with dynamic to defer compile-time type checking until run-time. Since I know I can combine any variation in a 2 operand expression of int, float and string in common operations, this works out really well.

Example of addition method:

private string Addition<T>(T left, T right) 
{
	dynamic temp = left; 
	temp += right; 
	return temp.ToString(); 
}

In this way we don’t have to write multiple methods to cover all cases, just one method to handle it all, making the solution far more readable and maintainable.

I have this extended to other operations (-, *, /, %) in my evaluator found here, which has full source code available to see the whole process in action.

Wrapping Up

So hopefully this has been informative, if you’ve enjoyed reading please leave a comment below or see if I’ve made any mistakes or a better way of doing this I would love to hear it, thanks!