Calling a Function from a String in C#

Calling a function from a string in C#

Yes. You can use reflection. Something like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

With the above code, the method which is invoked must have access modifier public. If calling a non-public method, one needs to use the BindingFlags parameter, e.g. BindingFlags.NonPublic | BindingFlags.Instance:

Type thisType = this.GetType();
MethodInfo theMethod = thisType
.GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);

Calling class object's function from string in c#

Yes that's possible via reflection. You can use the Invoke method.

It would look something like this:


MethodInfo method = type.GetMethod(name);
object result = method.Invoke(objectToCallTheMethodOn);

Having said that, in normal circumstances you shouldn't use reflection to call methods in c#. It's only for really special cases.


Here's a full example:

class A 
{
public int MyMethod(string name) {
Console.WriteLine( $"Hi {name}!" );
return 7;
}
}



public static void Main()
{
var a = new A();
var ret = CallByName(a, "MyMethod", new object[] { "Taekyung Lee" } );
Console.WriteLine(ret);
}

private static object CallByName(A a, string name, object[] paramsToPass )
{
//Search public methods
MethodInfo method = a.GetType().GetMethod(name);
if( method == null )
{
throw new Exception($"Method {name} not found on type {a.GetType()}, is the method public?");
}
object result = method.Invoke(a, paramsToPass);
return result;
}

This prints:

Hi Taekyung Lee!
7

How to call a function with a string variable in C#

Could this solution solve your problem?

    class Program
{
private static Dictionary<string, Action> _myMethods;

static Program()
{
_myMethods = new Dictionary<string, Action>();
_myMethods.Add("Greet", Greet);
}

static void Main(string[] args)
{

InvokeMethod("Greet");
Console.ReadKey();
}

private static void InvokeMethod(string methodNameToInvoke)
{
_myMethods[methodNameToInvoke].Invoke();
}

private static void Greet()
{
Console.WriteLine("Hello there!");
}
}

Calling a function from another namespace from a string C#

Based on "Sticky bit" answer:

Type thisType = Type.GetType("System.Console");
MethodInfo theMethod = thisType.GetMethod("WriteLine");

theMethod.Invoke(null, new object[1] { "Hello" });

But you have to be careful about method overloads, because then you can get

System.Reflection.AmbiguousMatchException

Also, this aproach isnt the best, and it's a sign of a design problem.
Another thing to take in mind, is using "nameof" operator to tell namespaces names and methods, that's to avoid magic strings.
Applying this on the example i gave:

Type thisType = Type.GetType(nameof(System) + "." + nameof(Console));
MethodInfo theMethod = thisType.GetMethod(nameof(Console.WriteLine));

theMethod.Invoke(null, new object[1] { "Hello" });

Then the caller:

CallMethodFromName(nameof(Console) + "." + nameof(Console.WriteLine), "Hello, world!");

calling the function, which is stored in a string variable

In order to call a function you need to specify the type this function is declared on. If all functions you are going to call are declared on a common class you could do the following:

static void CallFunc(string mymethod)
{
// Get a type from the string
Type type = typeof(TypeThatContainsCommonFunctions);

// 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);
}

If the functions you are going to call are static you don't need an instance of the type:

static void CallFunc(string mymethod)
{
// Get a type from the string
Type type = typeof(TypeThatContainsCommonFunctions);

// Retrieve the method you are looking for
MethodInfo methodInfo = type.GetMethod(mymethod);

// Invoke the method on the type
methodInfo.Invoke(null, null);
}

C# Calling Math Function from String

As I see here you have 3 problems with your code

  1. Math is class not a type so you should call typeof(Math) instead of Math.GetType() to get the Type
  2. Ambiguous method - Math.Round() as a-lot of overload, so you specify the overload that you want to use with GetMethod(String, Type[]), for example Math.Round(Double), so you should write MethodInfo method = typeof(Math).GetMethod(mathFunc, new[] {typeof(double) }) ;
  3. method.Invoke(this,... ) should be replcaed with method.Invoke(null, ..), although using this is acceptale Math.round is static, and the first object paramter will be ingoned anyway.

So full code can be something like this

            string mathFunc = "Round";    
MethodInfo method = typeof(Math).GetMethod(mathFunc, new[] {typeof(double) }) ;
var res = method.Invoke(null, new object[] { 1.78d });
Console.WriteLine(res);

Output : 2

dotnetfiddle



Related Topics



Leave a reply



Submit