I have been asked how you can call a method given its name in a string variable using reflection. Here is a code sample showing how to do it.
using System;
using System.Reflection;
namespace CallMethodByNameWithReflection
{
class MyClass
{
public void SayHello()
{
Console.WriteLine("Hello World!");
}
}
class Program
{
public static void CallMethod(object o, string MethodName)
{
var t = o.GetType();
var mi = t.GetMethod(MethodName);
mi.Invoke(o, null);
}
static void Main(string[] args)
{
var c = new MyClass();
CallMethod(c, "SayHello");
}
}
}