Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math operations on arbitrary objects in C#

Tags:

c#

object

I'm implementing an interpreter for a toy language in C#, and in order to do math in that language I'd like to implement a function like this:

public static object Add( object a, object b )
{
  // return the sum of a and b
  // each might be int, double, or one of many other numeric types
}

I can imagine a very silly and bad implementation of this function with tons of branches based on the types of a and b (using the is operator) and a bunch of casts, but my instinct is that there is a better way.

What do you think a good implementation of this function would be?

like image 983
Harold Avatar asked Nov 28 '22 15:11

Harold


1 Answers

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.

like image 189
Eric Lippert Avatar answered Dec 10 '22 10:12

Eric Lippert