BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Delegates

The fourteenth part of the C# Object-Oriented Programming tutorial explains how to add delegates to classes and programs. Delegates are used to provide references to methods that may be altered at run-time. They are also essential when creating events.

Referencing Multiple Methods

Adding the first method to the delegate uses the same syntax used in the previous example. To add the second and subsequent method references, the addition compound assignment operator (+=) is used. The following code shows this by executing both of the status display methods from a single delegate call. To test the sample, replace the contents of the Main method with the code below:

Scoreboard board = new Scoreboard();

ShowStatus points = new ShowStatus(board.PointsAwarded);
ShowStatus hit = new ShowStatus(board.TargetHit);

ShowStatus display = points;
display += hit;

display();

/* OUTPUT

Points awarded!
Target hit!

*/

In this code, an instance of Scoreboard is needed so this is declared first, followed by an individual declaration for two delegates to reference the two methods. The "display" delegate, which will be the multicast delegate is then created and assigned the value of "points". Using the compound assignment operator the second delegate is added to the invocation chain so that when display is called, both of the underlying methods are executed.

Removing the References

As with simple delegates it is important to release the references when they are no longer required. To release all of the references at once, the delegate objects can be simply set to null as described earlier. However, sometime you will want to unsubscribe single references. This is achieved by using the subtraction compound operator. For example, to unsubscribe and release the "points" reference, you would use the following code:

display -= points;
points = null;
27 January 2008