Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically call a class' method in .NET?

Tags:

c#

reflection

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

like image 569
pistacchio Avatar asked Jul 13 '09 15:07

pistacchio


People also ask

Can we create a class dynamically in C#?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.

Can we pass dynamic as parameter in C#?

Yes, you can do that. As stated in C# 4.0 specification, the grammar is extended to support dynamic wherever a type is expected: type: ...


2 Answers

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.

like image 101
Andrew Hare Avatar answered Sep 19 '22 11:09

Andrew Hare


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.

like image 36
Kenan E. K. Avatar answered Sep 18 '22 11:09

Kenan E. K.