Monday, October 11, 2010

Invoke a Method when method name is in string format or stored in variable

Below is the code that will do the trick, wrapped in the method InvokeStringMethod. As you see, it takes only two lines to call another method given its name as a string, and its class name also as a string. Read the comments in the code to see how it works.

public static string InvokeStringMethod(string typeName, string methodName)
// Get the Type for the class
Type calledType = Type.GetType(typeName);

// Invoke the method itself. The string returned by the method winds up in s
String s = (String)calledType.InvokeMember(
BindingFlags.InvokeMethod | BindingFlags.Public |

// Return the string that was returned by the called method.
return s;

This method assumes that the called method has no parameters and returns a string. Pass the name of the method in parameter methodName, and the name of its class in typeName.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MyNameSpace

public class MyClass
public int returnvalue(int x)
return x;

class Program

static void Main(string[] args)
string s ="returnvalue";
Type t = typeof(MyClass);
ConstructorInfo CI = t.GetConstructor(new Type[] {});
object o = CI.Invoke(new object[]{});
MethodInfo MI = t.GetMethod(s);
object[] fnargs = new object[] {4};
Console.WriteLine("Function Returned values: " +MI.Invoke(o, fnargs).ToString());



Share This!

No comments:

Powered By Blogger · Designed By Seo Blogger Templates