Calling a method from a string in C# (dynamic method invocation)

C

We are often used to call methods dynamically. You can invoke methods of a class instance using reflection, doing a dynamic method invocation. The following code snipped presents an easy way of invocation in C#.

public void Execute(string methodName, object[] args)
{
   if (GetType().GetMethod(methodName)) != null)
   {
      MethodInfo method = GetType().GetMethod(methodName);
      method.Invoke(this, new object[] { arg });
   }
}

//
//

public void myMethod(object[] arg)
{
...
...
}

What is invocation?

For a method invocation, the primary-expression of the invocation-expression must be a method group. The method group identifies the one method to invoke or the set of overloaded methods from which to choose a specific method to invoke. In the latter case, determination of the specific method to invoke is based on the context provided by the types of the arguments in the argument-list.

https://msdn.microsoft.com/en-us/library/aa691356(v=vs.71).aspx

Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags