Skip to content

Removing Methods from a Delegate

You can also remove a method from a delegate, using the -= operator. The following line of code shows the use of the operator. Figure 2 shows the result of this code when applied to the delegate illustrated in Figure 1.

Figure 1
Figure 2 Result of removing a method from a delegate

As with adding a method to a delegate, the resulting delegate is actually a new delegate. The new delegate is a copy of the old delegate—but its invocation list no longer contains the reference to the method that was removed.

The following are some things to remember when removing methods:

  • If there are multiple entries for a method in the invocation list, the -= operator starts
    searching at the bottom of the list and removes the first instance of the matching
    method it finds.
  • Attempting to delete a method that is not in the invocation list has no effect.
  • Attempting to invoke an empty delegate throws an exception. You can check whether
    a delegate’s invocation list is empty by comparing the delegate to null. If the
    invocation list is empty, the delegate is null.

Leave a Reply

Your email address will not be published. Required fields are marked *