15

How to pass a class and a method name as strings and invoke that class' method?

Like

void caller(string myclass, string mymethod){
    // call myclass.mymethod();
}

Thanks

3 Answers 3

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()
    {
        Console.WriteLine("Bar");
    }
}

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

Sign up to request clarification or add additional context in comments.

5 Comments

So long as the assembly is loaded and the typename is assembly-qualified, you're golden.
Hmm... I', finding your example to return null in "Type.GetType(myclass);"
That's because the assembly containing myclass isn't loaded into the appdomain yet. You'll have to get the assembly name from the caller and do Assembly.LoadFrom or one of the many variants to load the assembly first.
How would I approach calling Mailer.CallBack(xyz).Send(); I can see how to achieve calling everything apart from the .send() at the end? Any help appreciated.
Thanks for your help, I am getting error parameter count mismatch on methodInfo.Invoke(obj, null)
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 binding flags according to the method you wish to call, as well as check the Type.InvokeMember method in msdn to be certain of what you really need.

1 Comment

You are correct, my apologies. Edited to add method arguments which cannot be omitted (C# 4.0 where art thou) :)
-3

What's your reason for doing this? More than likely you can do this without reflection, up to and including dynamic assembly loading.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.