Monday, 9 April 2012

Beginning .Net : Call Overloaded method using reflection

Some time you need to call single or overloaded method using reflection.
Here are sample example for that :

Here I created sample class whose methods we call using reflection with overloaded methods
public class SampleClass
    {
        public string[] SampleMethod()
        {
            return new string[] { "Welcome", "Hello" };
        }
        public int SampleMethod(int intValue)
        {
            return intValue;
        }
    }

Now when you call method of this class using reflection you need to create object of this class
  SampleClass dummy = new SampleClass();

//Now call method without parameter

        string[] ret ;
        MethodInfo  theMethod = dummy.GetType().GetMethod("SampleMethod", new Type[0] );
        if (theMethod != null)
        {
               ret = (string[])theMethod.Invoke(dummy, null);
        }
//Now this ret variable get the return result of "SampleMethod()" method.
Output :
 ret[0]="Welcome"
 ret[0]="Hello"

//Now call method with parameter
         int ret;
         MethodInfo   theMethod = dummy.GetType().GetMethod("SampleMethod", new Type[] { typeof(int) });
        if (theMethod != null)
        {
            ret = (int)theMethod.Invoke(dummy, new object[] {5});
        }

//Now this ret variable get the return result of parametarized "SampleMethod(int intValue))" method.

Output :
ret = 5

Using this you can also call more than one parameter value by passing array of it's argument value types.

No comments:

Post a Comment