CSharp - Delegate Multicast Delegates


delegate instances have multicast capability.

A delegate instance can reference a list of target methods.

The + and += operators combine delegate instances.

For example:

SomeDelegate d = SomeMethod1;
d += SomeMethod2;

The last line is functionally the same as:

d = d + SomeMethod2;

Invoking d will now call both SomeMethod1 and SomeMethod2.

Delegates are invoked in the order they are added.

The - and -= operators remove the right delegate operand from the left delegate operand.

For example:

d -= SomeMethod1;

Invoking d will now cause only SomeMethod2 to be invoked.

Calling + or += on a null delegate variable is equivalent to assigning the variable to a new value:

SomeDelegate d = null;
d += SomeMethod1;       // Equivalent (when d is null) to d = SomeMethod1;

Calling -= on a delegate variable with a single target is equivalent to assigning null to that variable.

Delegates are immutable, calling += or -= creates a new delegate instance and assigns it to the existing variable.

If a multicast delegate has a nonvoid return type, the caller receives the return value from the last method to be invoked.

The preceding methods are still called, but their return values are discarded.

Related Topics