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?
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.
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.
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.
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");
}
}
Yes You can use reflection to find the method and invoke with proper arguements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With