14.4. Removing delegates

As well as combining, you can also remove methods from a delegate instance using the - operator. It is possible to have a delegate instance with no method in its invocation list. However, when such a delegate instance is invoked, a System.NullReferenceException is thrown.

It is also possible to have a method in the list more than once. For example, this statement is perfectly legal:

MyDelegate compositeDelegate = d1 + d1;

When you attempt to remove a method which does not exist in the invocation list, nothing happens.

When you remove a method which occurs more than once in the list, the last is removed. Assuming that d1, d2, and d3 represent delegate instances encapsulating Method1, Method2, and Method3 respectively, ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.