Removing delegates is the opposite of combining them.
To remove a delegate from a combined delegate:
To remove a delegate, you must have two variables : one that stores a combination of delegates and one that points to the delegate object you want to remove from the list.
Type the name of the variable that has the combined delegate.
Type -= (minus equal operator).
Type the name of the variable you want to remove from the list of delegates.
Type a semicolon ; ( Figure 10.9 ).
Figure 10.9 With the -= operator we can remove one of the delegates from the combined delegate. Therefore, calling t3 now only invokes Task2.
class Tasks { public bool Task1(string desc) { return true; } public static bool Task2(string desc) { return true; } } delegate bool TaskDel(string desc); public class WebForm1 : System.Web.UI.Page { private void Page_Load(object sender, System.EventArgs e) { Tasks tsks = new Tasks(); TaskDel t1 = new TaskDel( tsks.Task1); TaskDel t2 = new TaskDel( Tasks.Task2); bool result; result = t1("Calling Task 1..."); result = t2("Calling Task 2..."); TaskDel t3 = t1 + t2; t3("Call both delegates..."); t3 -= t1; t3("Call only Task2..."); } }
Tips
When you use the -= operator, the C# compiler turns that code into a call to the delegate's Remove function, which lets you remove a delegate from a linked list of delegates.
The ability of delegates to be combined and removed makes it easy to build a subscriber class such as the Modem class ( Figure 10.10 ). This class reports information for the status of the modem, and multiple classes can subscribe to receive notifications. The Modem class has a method called Subscribe and a method called Unsubscribe to enable other classes to request and cancel notifications.
Figure 10.10 The Modem class enables a user to request modem status as the modem is connecting. The Modem class has a Subscribe method that enables a user to pass a delegate variable. The Connect method then uses this variable to call a function on the subscriber's class.
delegate void ReportStatusDel( string status); class Modem { static ReportStatusDel report; public static void Subscribe ( ReportStatusDel del) { report += del; } public static void Unsubscribe ( ReportStatusDel del) { report -= del; } public static void Connect() { if (report != null) { report("Initializing..."); report("Dialing..."); report("Authenticating..."); report("Connected..."); } } } public class WebForm1 : System.Web.UI.Page { private void ReportModemStatus ( string msg) { Response.Write(msg + "<br>"); } private void Page_Load(object sender, System.EventArgs e) { Modem.Subscribe( new ReportStatusDel( ReportModemStatus)); Modem.Connect(); Modem.Unsubscribe( new ReportStatusDel( ReportModemStatus)); } }