Multicast Delegates - CSharp Custom Type

CSharp examples for Custom Type:delegate

Introduction

All delegate instances have multicast capability.

This means that a delegate instance can reference not just a single target method, but also 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 delegate variable with a null value works, and it is equivalent to assigning the variable to a new value:

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

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

Delegates are immutable, so when you call += or -=, you're creating a new delegate instance and assigning it to the existing variable.


Related Tutorials