Just finished reading Jon Skeet’s article about events and delegates and got a question.
Lets say first in the code I declare an event
public event EventHandler MyEvent
Then I want to raise it in the code in a manner
if (MyEvent != null)
Myevent(this,EvtArgs.Empty);
Jon says that in fact MyEvent looks somehow like this:
private EventHandler _myEvent;
public event EventHandler MyEvent
{
add
{
lock (this)
{
_myEvent += value;
}
}
remove
{
lock (this)
{
_myEvent -= value;
}
}
}
The question is what really happens when I compare MyEvent != null ?
As I understand in fact it compares _myEvent to null, but I am not sure.
If you implement custom add/remove accessors, you won’t be able to compare
MyEventto null in the first place, because it will only be an event – it doesn’t have a value as such, only add/remove accessors. You would have to use your declared field (_myEventin the sample above) instead.You can only do the comparison using the event name when you’re using field-like events, where you end up with (effectively) a field and an event with the same name. (The compiled code doesn’t have to actually reuse the event name for the field name, but it has to look like it does when you’re compiling.)
Note that using this:
isn’t thread-safe, as
MyEventcould become null between the check and the invocation. You should use:Also note that the part about field-like events locking on
thisis now slightly outdated; in C# 4 thread-safety is achieved using a lock-free compare-exchange mechanism.