Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Help reflecting operator methods

$
0
0

Hi.
I need to invoke the Addition operator in a given object (if exist) in order to perform a sum.
The object parameters are System.Object types so i don't know if they really has the operator implemented, so i used reflection:

public static object Add(object x, object y)
{
	var xType = x.GetType();
	MethodInfo op = xType.GetMethod("op_Addition");
	if (op == null)
	{
		throw new InvalidOperationException("Some error");
	}
	return op.Invoke(x, new object[] { x, y });
}

But what happens when the objects are primitive types like Int32? I red this article and they say "Int32 (and the other primitive types) don't have operator methods; they use specific CIL instructions instead."

So my solution to the problem was verify if the type is a primitive type then use 'dynamic' keyword to call the method:

public static object Add(object x, object y)
{
	dynamic dynX = (dynamic)x;
	dynamic dynY = (dynamic)y;
	return dynX + dynY;
}

I'm not very sure what happens there but it worked.

What i'm asking is:

1. Is there a better approach to my problem? I've seen solutions like parse the object to its proper type but that is no solution in my case. I have to use reflections because there are a lot of primitive types that can be added via the '+' operator.

2. What actually happens when i parse the parameters using the 'dynamic' keyword? I'm worried about if solving my problem using this approach i'm creating a bigger one that can not be seen easily. I think this is no the scenario for what the 'dynamic' was added to the language.

Thanks a lot.


Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>