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
- Math is class not a type so you should call
typeof(Math)
instead ofMath.GetType()
to get theType
- 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 writeMethodInfo method = typeof(Math).GetMethod(mathFunc, new[] {typeof(double) }) ;
method.Invoke(this,... )
should be replcaed withmethod.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
Difference Between the | and || or Operators
Why Are Cdecl Calls Often Mismatched in the "Standard" P/Invoke Convention
What Are the Differences Between Generics in C# and Java... and Templates in C++
Graph Nodes Coordinates Evaluation
How to Get Started With Developing Internet Explorer Extensions
How to Load Dll (Module Could Not Be Found Hresult: 0X8007007E)
Pre & Post Increment Operator Behavior in C, C++, Java, & C#
How to Specify a [Dllimport] Path At Runtime
Possible to Call C++ Code from C#
What Do 'Statically Linked' and 'Dynamically Linked' Mean
Passing Strings from C# to C++ Dll and Back - Minimal Example
Using a Class Defined in a C++ Dll in C# Code
Is Is Possible to Export Functions from a C# Dll Like in VS C++
What Does the Unary Plus Operator Do