In this article, we will discuss the methodinfo.invoke in C# with its syntax, parameter, and example.
What is the Methodinfo.Invoke?
The Method.info.Invoke C#'s method lets us to call an object's method dynamically during runtime. This method is a component of the .NET framework's reflection capabilities, which let us dynamically inspect and modify code.
Methods:
Dynamic Calling: Information about the Method.Runtime dynamic method invocation on objects is enabled by the Invoke function. It is a component of the .NET framework's reflection features.
Syntax:
public object? Invoke(object? obj, object?[] parameters);
- obj: The object on which the method will be called on. For static methods is null.
- Parameters: An array of objects that serve as the arguments for the method.
- The method represented by the MethodInfo object is dynamically executed.
- Like calling an Method method directly, but dynamic.
- Returns an object that is a representation of the called method's return value.
- For methods with a return type of void is null.
- It carries over exceptions that the called method has thrown.
- Its robustness requires proper handling of exceptions.
Execution:
Value Returned:
Handling Exceptions:
C# Code:
Let us take an example to illustrate the Methodinfo.invoke method in C#.
using System;
using System.Reflection;
public class MyClass
{
public void SayHello(string name)
{
Console.WriteLine($"Hello, {name}!");
}
public static int Add(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
// Creating an instance of MyClass
var myClassInstance = new MyClass();
// Get the type of MyClass
Type myClassType = typeof(MyClass);
// Get the method info for the SayHello method
MethodInfo sayHelloMethod = myClassType.GetMethod("SayHello");
// Invoking SayHello dynamically
sayHelloMethod.Invoke(myClassInstance, new object[] { "harsha" });
// Get the method info for the Add method
MethodInfo addMethod = myClassType.GetMethod("Add");
// Invoking Add dynamically
int result = (int)addMethod.Invoke(null, new object[] { 5, 3 });
Console.WriteLine($"Result of addition: {result}");
}
}
Output:
Hello, harsha!
Result of addition: 8
Explanation:
- In this example, SayHello and Add are the two methods in the MyClass class that we use.
- An instance method called SayHello prints a greeting after receiving a string parameter.
- Add is a static method that returns the sum of two integer parameters when given two.
Within the main method:
- We establish a new MyClass
- For the SayHello and Add methods, use reflection to obtain MethodInfo objects.
- Utilizing MethodInfo , call these methods dynamically. As Add is a static method, we pass null and the instance for SayHello along with the necessary parameters when calling Invoke.
Example 2:
Let us take another example to illustrate the Methodinfo.invoke method in C#.
using System;
using System.Reflection;
public class Car
{
public void StartEngine()
{
Console.WriteLine("Engine started!");
}
public void Accelerate(int speed)
{
Console.WriteLine($"Accelerating at {speed} km/h.");
}
public void Brake()
{
Console.WriteLine("Brakes applied.");
}
}
class Program
{
static void Main(string[] args)
{
// Create an instance of the Car class
Car myCar = new Car();
// Get the type of Car
Type carType = typeof(Car);
// Get the MethodInfo for each method
MethodInfo startMethod = carType.GetMethod("StartEngine");
MethodInfo accelerateMethod = carType.GetMethod("Accelerate");
MethodInfo brakeMethod = carType.GetMethod("Brake");
// Invoke each method dynamically
startMethod.Invoke(myCar, null);
accelerateMethod.Invoke(myCar, new object[] { 60 });
brakeMethod.Invoke(myCar, null);
}
}
Output:
Engine started!
Accelerating at 60 km/h.
Brakes applied.
Explanation:
- In this example, the three methods in our Car class are StartEngine, Accelerate , and Brake .
- A message stating that the engine has been started is printed by StartEngine .
- Using an integer parameter for speed, the function accelerate prints an acceleration-indicating message.
- The brake applies and prints a message indicating this.
Within the main method:
- We start by making a Car instance.
- Get the MethodInfo objects for each method by using reflection.
- Use MethodInfo to call each method dynamically. Pass the Car instance and any required parameters (if any) to invoke.
Conclusion
In conclusion, the methodinfo.invoke in C#'s function offers a robust mechanism for dynamic method invocation, allowing programmers to work with types and methods in runtime via reflection. Developers can dynamically call a method within a type by obtaining a MethodInfo object representing that method and passing in the required arguments as an array of objects. Due to its flexibility, a multitude of dynamic behaviors is possible, including the implementation of generic frameworks with dynamically determined behavior, loading and executing modules or extensions, and invoking methods based on user input. But using MethodInfo is very crucial in C#. Use invoke carefully since relying too much on reflection can slow down operations and make the code tougher to understand. When calling methods dynamically, it's also essential to handle exceptions properly because they propagate and need to be handled correctly. In general, MethodInfo.Invoke gives developers dynamic capabilities; however, performance, readability, and robustness should all be taken into account when utilizing it.