Call class methods using the method name dynamically

By Hiren Soni Aug 28 2010
This blog talks about how we can call a class method using strong method name at run-time.
    • Like
    • Love It
    • Awesome
    • Interesting
    • It's Okay
    • Thumbs Down
  • 6.7k
  • 0

We can use reflection to call a class and its methods and properties using method and property names. Here is an example where we call a method using the method name.

Before you use this approach, you must import System.Reflection namespace.

using System.Reflection;

Here we create a instance of the class and gets a method instance using the GetMethod method. The Invoke method executes the method.

classdemo c1 = new classdemo();
MethodInfo mi = typeof(classdemo).GetMethod("functionname_in_string_format");
mi.Invoke(c1, null);