How to use the invoke method in C#?

In C#, the Invoke method can be used to call a delegate or a parameterless method.

Firstly, it is necessary to define a delegate whose parameters and return value match those of the method to be called. For example, if calling a method with no parameters, a delegate can be defined as follows:

delegate void MyMethodDelegate();

Then, you can create a delegate instance and pass the method to be called as a parameter to the delegate.

MyMethodDelegate myDelegate = MyMethod;

Next, you can use the Invoke method to call the delegate instance, which will trigger the corresponding method.

myDelegate.Invoke();

The complete sample code is shown below:

using System;

namespace InvokeExample
{
    delegate void MyMethodDelegate();

    class Program
    {
        static void Main(string[] args)
        {
            MyMethodDelegate myDelegate = MyMethod;
            myDelegate.Invoke();
        }

        static void MyMethod()
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

In the above code, a parameterless method named MyMethod is defined, and a MyMethodDelegate delegate instance is created in the Main method. The Invoke method is used to call this delegate instance, which will output “Hello, World!” in the end.

bannerAds