[ACCEPTED]-How to dynamically call a class' method in .NET?-reflection

Accepted answer
Score: 34

You will want to use reflection.

Here is a simple example:

using System;
using System.Reflection;

class Program
    static void Main()
        caller("Foo", "Bar");

    static void caller(String myclass, String mymethod)
        // Get a type from the string 
        Type type = Type.GetType(myclass);
        // Create an instance of that type
        Object obj = Activator.CreateInstance(type);
        // Retrieve the method you are looking for
        MethodInfo methodInfo = type.GetMethod(mymethod);
        // Invoke the method on the instance we created above
        methodInfo.Invoke(obj, null);

class Foo
    public void Bar()

Now 5 this is a very simple example, devoid of error 4 checking and also ignores bigger problems 3 like what to do if the type lives in another 2 assembly but I think this should set you 1 on the right track.

Score: 9

Something like this:

public object InvokeByName(string typeName, string methodName)
    Type callType = Type.GetType(typeName);

    return callType.InvokeMember(methodName, 
                    BindingFlags.InvokeMethod | BindingFlags.Public, 
                    null, null, null);

You should modify the 4 binding flags according to the method you 3 wish to call, as well as check the Type.InvokeMember 2 method in msdn to be certain of what you 1 really need.

More Related questions