MichaC
MichaC

Reputation: 2844

Event Invocators in C#

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?

Upvotes: 6

Views: 1801

Answers (3)

Reed Copsey
Reed Copsey

Reputation: 564641

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!
}

Upvotes: 2

Brian Genisio
Brian Genisio

Reputation: 48147

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.

Upvotes: 5

John Saunders
John Saunders

Reputation: 161791

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.

Upvotes: 8

Related Questions