Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a method thats name was passed as a string

Tags:

c#

I have a C# method that takes a string as an argument, that string contains the name of a static method e.g

"MyClass.GetData"

Is it possible to run that method from the value passed in the string?

like image 814
Gavin Avatar asked Aug 18 '09 10:08

Gavin


People also ask

How can I call a function given its name as a string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How to call a method from a method in C#?

In order to call method, you need to create object of containing class, then followed bydot(.) operator you can call the method. If method is static, then there is no need to create object and you can directly call it followed by class name.

What is an instance method C#?

Non-static method or instance method is defined without static keyword as I have defined below. The non-static method is called by making an object of the class. We can use this keyword inside the static function. The non-static method uses a memory of the object.


2 Answers

yes you can using System.Reflection


CallStaticMethod("MainApplication.Test", "Test1");

public  static void CallStaticMethod(string typeName, string methodName)
{
    var type = Type.GetType(typeName);

    if (type != null)
    {
        var method = type.GetMethod(methodName);

        if (method != null)
        {
            method.Invoke(null, null);
        }
    }
}

public static class Test
{
    public static void Test1()
    {
        Console.WriteLine("Test invoked");
    }
}
like image 110
Hath Avatar answered Oct 26 '22 16:10

Hath


Yes You can use reflection to find the method and invoke with proper arguements.

like image 33
Ashok Ralhan Avatar answered Oct 26 '22 14:10

Ashok Ralhan