How to dynamically call a method in C#?

If the functions are known at compile time and you just want to avoid writing a switch statement.

Setup:

Dictionary<string, Func<int, int, int>> functions =
  new Dictionary<string, Func<int, int, int>>();

functions["add"] = this.add;
functions["subtract"] = this.subtract;

Called by:

string functionName = "add";
int x = 1;
int y = 2;

int z = functions[functionName](x, y);

how can i do this in c#?

Using reflection.

add has to be a member of some type, so (cutting out a lot of detail):

typeof(MyType).GetMethod("add").Invoke(null, new [] {arg1, arg2})

This assumes add is static (otherwise first argument to Invoke is the object) and I don't need extra parameters to uniquely identify the method in the GetMethod call.


Use reflection - try the Type.GetMethod Method

Something like

MethodInfo addMethod = this.GetType().GetMethod("add");
object result = addMethod.Invoke(this, new object[] { x, y } );

You lose strong typing and compile-time checking - invoke doesn't know how many parameters the method expects, and what their types are and what the actual type of the return value is. So things could fail at runtime if you don't get it right.

It's also slower.


You can use reflection.

using System;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Type t = p.GetType();
            MethodInfo mi = t.GetMethod("add", BindingFlags.NonPublic | BindingFlags.Instance);
            string result = mi.Invoke(p, new object[] {4, 5}).ToString();
            Console.WriteLine("Result = " + result);
            Console.ReadLine();
        }

        private int add(int x, int y)
        {
            return x + y;
        }
    }
}

Tags:

C#