tags:

views:

171

answers:

3

When I implement an event in Visual Studio, Resharper is kind enough to offer to create an event invocator for me. I usually did this by hand in the past, and my invocators always looked like this

    private void InvokePropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, e);
        }
    }

but the invocator created by Resharper looks like this (cleaned up a little by hand)

    private void InvokePropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler changed = PropertyChanged;

        if (changed != null)
        {
            changed(this, e);
        }
    }

Do the people at jetbrains know something about c# I don't? Is there some technical advantage to having the local variable, or is it just an artifact of them having to auto-generate the code?

+5  A: 

Yes. They know that the number of subscribers to an event can change between the "if" and the call to the event handler. They capture it in a local, where it doesn't change any more.

John Saunders
are u sure about that? dont both of them "point" to the same invocation list?
BFree
Not necessarily. The entire list could change, in general. Note that ReSharper is a "general" tool. You seem to be assuming the only thing that happens with the event is += and -=. Maybe yes, maybe no, but the "ReSharper" way covers all bases.
John Saunders
Actually the number of subscribers does not matter, that is taken care of by the delegate itself. The fact that the delegate is null if there are no subscribers, though, is important. If there is no subscribers, the field is null. You copy a null reference, so if a subscriber is added after the if you will just not see it by will not fail.
Denis Troller
+4  A: 

I think John Saunders probably has the best answer.

For the record, I don't even write "Invocators" anymore. I have extension methods that do it for me, and I just call PropertyChanged.Fire(this, "propName");

See this article for more info.

Brian Genisio
Hey, that's cool. Glad I asked.
MichaC
A: 

This is only an issue for multithreading. This protects you in a multithreaded environment.

For example, take this scenario:

if (PropertyChanged != null) // PropertyChanged has one subscriber here
{

Now, a second thread unsubscribes here, modifying the event handler....

    PropertyChanged(this, e); // This is no longer valid!
}
Reed Copsey