Delegate types are immutable types. If D
is an instance of a delegate type, it consists of a fixed-length invocation list with one or more items.
So you can't "clear" the list. You also cannot create a new instance with an empty invocation list because a null
reference (not an instance) is used for the case where no methods are present.
Example (MyMethod
and JonnysMethod
are method groups, not delegate variables):
Action D = null; // no object, no invocation list
D += MyMethod; // null and new Action(MyMethod) are combined; result is assigned to D
// D is an instance, invocation list length is 1
D += JonnysMethod; // two instances are combined; D is assigned to new instance; original instances are no longer referenced and will "soon" be garbage collected
// D is an instance, invocation list length is 2
D -= MyMethod; // D is assigned to a new instance again
D -= JonnysMethod; // D is assigned to null; no new instance
Take care: If D
is really an event, be careful. If you're outisde the class/struct where D
is defined, +=
and -=
are calls to the accessors of the event. So they are not immediate delegate combinations in this case. If you're inside the class/struct that defines D
, and if D
is a "field-like" event, D
can be used in two senses. As a delegate variable (the "hidden" backing field of the event), and as an event. The meaning of +=
and -=
can the be interpreted in two ways. Until C# 3, it was interpreted as delegate combinantion directly on the backing field. In C# 4 and C# 5, the semantic is changed and +=
and -=
are calls to the event accessors in this situation.