Methodinfo.Invoke() In C#

In this guide, we will explore the methodinfo.invoke function in C# along with its syntax, parameters, and a demonstration.

What is the Methodinfo.Invoke?

The Method.info.Invoke method in C# allows us to dynamically invoke an object's method at runtime. This functionality is part of the reflection features in the .NET framework, enabling dynamic examination and manipulation of code.

Methods:

Dynamic Invocation: Details on Method.Runtime's Functionality

Invoking methods dynamically on objects is facilitated by the Invoke method, which forms part of the reflection capabilities within the .NET framework.

Syntax:

Example

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.
  • Execution:

  • The method represented by the MethodInfo object is dynamically executed.
  • Like calling an Method method directly, but dynamic.
  • Value Returned:

  • Returns an object that is a representation of the called method's return value.
  • For methods with a return type of void is null.
  • Handling Exceptions:

  • It carries over exceptions that the called method has thrown.
  • Its robustness requires proper handling of exceptions.
  • C# Code:

Let's consider a scenario to demonstrate the utilization of the Methodinfo.invoke function in the C# programming language.

Example

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:

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's consider another instance to demonstrate the utilization of the Methodinfo.invoke method in the C# programming language.

Example

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:

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 summary, the methodinfo.invoke function in C# provides a powerful feature for executing methods dynamically using reflection, enabling developers to interact with types and methods at runtime. By obtaining a MethodInfo object that represents a specific method and passing the necessary arguments as an array of objects, programmers can dynamically invoke methods within a type. This approach offers a wide range of dynamic functionalities, such as creating generic frameworks with adaptable behaviors, loading and running modules or extensions, and triggering methods based on user input. It is essential to exercise caution when utilizing invoke, as excessive reliance on reflection can lead to performance degradation and code complexity. Proper exception handling is crucial when invoking methods dynamically, as errors can propagate and must be managed effectively. While MethodInfo.Invoke empowers developers with dynamic capabilities, it is vital to consider performance, readability, and reliability when incorporating this feature.

Input Required

This code uses input(). Please provide values below: