Calling a function from a string in C#

C#.NetPhpStringFunction Calls

C# Problem Overview


I know in php you are able to make a call like:

$function_name = 'hello';
$function_name();

function hello() { echo 'hello'; }

Is this possible in .Net?

C# Solutions


Solution 1 - 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);

Solution 2 - C#

You can invoke methods of a class instance using reflection, doing a dynamic method invocation:

Suppose that you have a method called hello in a the actual instance (this):

string methodName = "hello";

//Get the method information using the method info class
 MethodInfo mi = this.GetType().GetMethod(methodName);

//Invoke the method
// (null- no parameter for the method call
// or you can pass the array of parameters...)
mi.Invoke(this, null);

Solution 3 - C#

class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(MyReflectionClass);
            MethodInfo method = type.GetMethod("MyMethod");
            MyReflectionClass c = new MyReflectionClass();
            string result = (string)method.Invoke(c, null);
            Console.WriteLine(result);

        }
    }

    public class MyReflectionClass
    {
        public string MyMethod()
        {
            return DateTime.Now.ToString();
        }
    }

Solution 4 - C#

This code works in my console .Net application

class Program
{
	static void Main(string[] args)
	{
		string method = args[0]; // get name method
		CallMethod(method);
	}
	
	public static void CallMethod(string method)
	{
		try
		{
			Type type = typeof(Program);
			MethodInfo methodInfo = type.GetMethod(method);
			methodInfo.Invoke(method, null);
		}
		catch(Exception ex)
		{
			Console.WriteLine("Error: " + ex.Message);
			Console.ReadKey();
		}
	}
	
	public static void Hello()
	{
		string a = "hello world!";
		Console.WriteLine(a);
		Console.ReadKey();
	}
}

Solution 5 - C#

A slight tangent -- if you want to parse and evaluate an entire expression string which contains (nested!) functions, consider NCalc (http://ncalc.codeplex.com/ and nuget)

Ex. slightly modified from the project documentation:

// the expression to evaluate, e.g. from user input (like a calculator program, hint hint college students)
var exprStr = "10 + MyFunction(3, 6)";
Expression e = new Expression(exprString);

// tell it how to handle your custom function
e.EvaluateFunction += delegate(string name, FunctionArgs args) {
		if (name == "MyFunction")
			args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate();
	};

// confirm it worked
Debug.Assert(19 == e.Evaluate());

And within the EvaluateFunction delegate you would call your existing function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremy BoydView Question on Stackoverflow
Solution 1 - C#ottobarView Answer on Stackoverflow
Solution 2 - C#Christian C. SalvadóView Answer on Stackoverflow
Solution 3 - C#BFreeView Answer on Stackoverflow
Solution 4 - C#ranobeView Answer on Stackoverflow
Solution 5 - C#drzausView Answer on Stackoverflow