CSharp - delegate create and invoke


A delegate instance is a delegate for the caller.

The caller invokes the delegate, and then the delegate calls the target method.

This indirection decouples the caller from the target method.

Suppose we have the following definition:

delegate int ConverterFunction (int x);

class Test
       static void Main()
         ConverterFunction t = Square;    // Create delegate instance
         int result = t(3);               // Invoke delegate
         Console.WriteLine (result);      // 9
       static int Square (int x) => x * x;

The statement:

ConverterFunction t = Square;

is shorthand for:

ConverterFunction t = new ConverterFunction (Square);

The expression:


is shorthand for:


All delegate types implicitly derive from System.MulticastDelegate, which inherits from System.Delegate.

C# compiles +, -, +=, and -= operations made on a delegate to the static Combine and Remove methods of the System.Delegate class.

Related Topics