Event = null;

  • Thread starter Thread starter Bruce Wood
  • Start date Start date
B

Bruce Wood

I need to remove all handlers from a particular event. I am doing this
in the class where the event is defined.

I have this vague memory that I can say:

this.MyEvent = null;

and this will clear all delegates from the event, but I'm not sure, and
I can't find the relevant documentation.

Can I do that, or do I have to loop through each delegate like this:

foreach (Delegate d in this.MyEvent.GetInvocationList())
{
this.MyEvent -= d;
}

?
 
Bruce Wood said:
I need to remove all handlers from a particular event. I am doing this
in the class where the event is defined.

I have this vague memory that I can say:

this.MyEvent = null;

and this will clear all delegates from the event, but I'm not sure, and
I can't find the relevant documentation.

Yes, you can - *if* the event has been declared as a "field-like" event
within the same class.
Can I do that, or do I have to loop through each delegate like this:

foreach (Delegate d in this.MyEvent.GetInvocationList())
{
this.MyEvent -= d;
}

Basically, a "field-like" event is actually two things:
1) The event (a pair of add/remove methods)
2) A delegate variable

You can do what you like to a delegate variable, but the only things
you can do with an event are add and remove handlers (and fire the
event, in theory, but C# doesn't implement that part itself).

What you *can't* do is clear an event declared in another class (even a
base class) with your first try - nor can you get the invocation list.
From the point of view of any other class (at compile-time; reflection
is a different story) the event is *just* an event.
 
So, just to clarify, if I have within my class:

protected event System.EventHandler UpdateBeginning;
protected event System.EventHandler UpdateEnded;

then I can do this:

protected void BeginUpdate()
{
if (this.UpdateBeginning != null)
{
this.UpdateBeginning(this, System.EventArgs.Empty);
}
this.UpdateEnded = null;
this._updateInProgress = true;
}

and the this.UpdateEnded = null will clear all events from the
"UpdateEnded" delegate?
 
That's correct.

Within your class, "UpdateEnded" refers to a compiler-created field
whose type is EventHandler, so you can set it to null and forget all
the delegates that have been added. It's only outside your class that
UpdateEnded refers to an event (and thus can only be used with += and
-=).

Jesse
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top