Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Invocators in C#

Tags:

c#

events

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?

like image 714
MichaC Avatar asked Apr 24 '09 00:04

MichaC


1 Answers

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.

like image 73
John Saunders Avatar answered Sep 19 '22 10:09

John Saunders