Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where is op_addition in [int,float,double]

Tags:

c#

Dummy code:

public object Addition(object a, object b)
{
    var type = a.GetType();
    var op = type.GetMethod("op_Addition", BindingFlags.Static | BindingFlags.Public);
    return op.Invoke(null, new object[] { a, b });
}

This method complains with int/float/double,that can't find these methods(op_Addition).

So how to build a general addition method?

like image 229
Vontio Avatar asked Jun 22 '12 11:06

Vontio


1 Answers

Yes, they're not custom operators which exist as members like that - there are built-in IL instructions instead.

(The same is almost true for string concatenation, except there the C# compiler builds a call to string.Concat.)

If you're using C# 4 and .NET 4, the simplest approach is to use dynamic typing:

public dynamic Addition(dynamic x, dynamic y)
{
    return x + y;
}

For earlier versions, you'll need to special-case certain types :(

It's not clear what your context is, but you may find Marc Gravell's article on generic operators interesting.

like image 121
Jon Skeet Avatar answered Nov 15 '22 05:11

Jon Skeet