Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Reflection to Invoke an Overloaded Method in .NET

Is there a way to Invoke an overloaded method using reflection in .NET (2.0). I have an application that dynamically instantiates classes that have been derived from a common base class. For compatibility purposes, this base class contains 2 methods of the same name, one with parameters, and one without. I need to call the parameterless method via the Invoke method. Right now, all I get is an error telling me that I'm trying to call an ambiguous method.

Yes, I could just cast the object as an instance of my base class and call the method I need. Eventually that will happen, but right now, internal complications will not allow it.

Any help would be great! Thanks.

like image 542
Wes P Avatar asked Oct 21 '08 21:10

Wes P


People also ask

What happens when an overloaded method is invoked?

Overloaded methods are differentiated based on the number and type of parameter passed as arguments to the methods. If we try to define more than one method with the same name and the same number of arguments then the compiler will throw an error.

Can you overload methods in C#?

In C#, there might be two or more methods in a class with the same name but different numbers, types, and order of parameters, it is called method overloading.

Can we overload a method in subclass?

Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.


2 Answers

You have to specify which method you want:

class SomeType  {     void Foo(int size, string bar) { }     void Foo() { } }  SomeType obj = new SomeType(); // call with int and string arguments obj.GetType()     .GetMethod("Foo", new Type[] { typeof(int), typeof(string) })     .Invoke(obj, new object[] { 42, "Hello" }); // call without arguments obj.GetType()     .GetMethod("Foo", new Type[0])     .Invoke(obj, new object[0]); 
like image 197
Hallgrim Avatar answered Sep 30 '22 21:09

Hallgrim


Yes. When you invoke the method pass the parameters that match the overload that you want.

For instance:

Type tp = myInstance.GetType();  //call parameter-free overload tp.InvokeMember( "methodName", BindingFlags.InvokeMethod,     Type.DefaultBinder, myInstance, new object[0] );  //call parameter-ed overload tp.InvokeMember( "methodName", BindingFlags.InvokeMethod,     Type.DefaultBinder, myInstance, new { param1, param2 } ); 

If you do this the other way round(i.e. by finding the MemberInfo and calling Invoke) be careful that you get the right one - the parameter-free overload could be the first found.

like image 37
Keith Avatar answered Sep 30 '22 21:09

Keith