If:
- you just want an easy-to-program solution
- your little language has the same arithmetic rules as C#
- you can use C# 4
- you don't care particularly about performance
then you can simply do this:
public static object Add(dynamic left, dynamic right)
{
return left + right;
}
Done. What will happen is when this method is called, the code will start the C# compiler again and ask the compiler "what would you do if you had to add these two things, but you knew their runtime types at compile time?" (The Dynamic Language Runtime will then cache the result so that the next time someone tries to add two ints, the compiler doesn't start up again, they just re-use the lambda that the compiler handed back to the DLR.)
If you want to implement your own rules for addition, welcome to my world. There is no magic road that avoids lots of type checks and switches. There are literally hundreds of possible cases for addition of two arbitrary types and you have to check them all.
The way we handle this complexity in C# is we define addition operators on a smaller subset of types: int, uint, long, ulong, decimal, double, float, all enums, all delegates, string, and all the nullable versions of those value types. (Enums are then treated as being their underlying types, which simplifies things further.)
So for example when you're adding a ushort to a short we simplify the problem by saying that ushort and short are both special cases of int, and then solve the problem for adding two ints. That massively cuts down on the amount of code we have to write. But believe me, the binary operator overload resolution algorithm in C# is many thousands of lines of code. It's not an easy problem.
If your toy language is intended to be a dynamic language with its own rules then you might consider implementing IDynamicMetaObjectProvider and using the DLR mechanisms for implementing arithmetic and other operations like function calling.