#1,018 – Delegate Invocation Syntax

In C#, you typically invoke a delegate by using the variable referring to the delegate instance as if it were a method.

For example, in the code below, the variable del1 is a delegate instance and you invoke it by using del1 as if it was a method.

        static void Method1(string text)
        {
            Console.WriteLine(text);
        }

        static void Main(string[] args)
        {
            StringHandlerDelegate del1 = Method1;

            // Invoke the delegate instance
            del1("Invoked through delegate");

            Console.ReadLine();
        }

Alternatively, you can call the Invoke method on the delegate instance.  This does exactly the same thing as the example above.

            // Invocation, method #2
            del1.Invoke("Also invoked thru delegate");
Advertisements