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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With