C# – Run a method thats name was passed as a string

c

I have a C# method that takes a string as an argument, that string contains the name of a static method e.g

"MyClass.GetData"

Is it possible to run that method from the value passed in the string?

Best Answer

yes you can using System.Reflection


CallStaticMethod("MainApplication.Test", "Test1");

public  static void CallStaticMethod(string typeName, string methodName)
{
    var type = Type.GetType(typeName);

    if (type != null)
    {
        var method = type.GetMethod(methodName);

        if (method != null)
        {
            method.Invoke(null, null);
        }
    }
}

public static class Test
{
    public static void Test1()
    {
        Console.WriteLine("Test invoked");
    }
}