Search code examples
.netdynamiclate-binding

Action<T> to call a method based on a string value


Is there a way to use Action to call a method based on a string value that contains the name of that method?


Solution

  • Action<T> is just a delegate type that could point to a given method. If you want to call a method whose name is known only at runtime, stored in a string variable, you need have to use reflection:

    class Program
    {
        static void Main(string[] args)
        {
            string nameOfTheMethodToCall = "Test";
            typeof(Program).InvokeMember(
                nameOfTheMethodToCall, 
                BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Static, 
                null, 
                null, 
                null);
        }
    
        static void Test()
        {
            Console.WriteLine("Hello from Test method");
        }
    }
    

    As suggested by @Andrew you could use Delegate.CreateDelegate to create a delegate type from a MethodInfo:

    class Program
    {
        static void Main(string[] args)
        {
            string nameOfTheMethodToCall = "Test";
            var mi = typeof(Program).GetMethod(nameOfTheMethodToCall, BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Static);
            var del = (Action)Delegate.CreateDelegate(typeof(Action), mi);
            del();
        }
    
        static void Test()
        {
            Console.WriteLine("Hello from Test method");
        }
    }