Home > Mobile >  Why is an additional EventHandler declared in this Microsoft Documentation?
Why is an additional EventHandler declared in this Microsoft Documentation?

Time:08-07

The Microsoft documentation on events includes the following example:

class Counter
{
    public event EventHandler ThresholdReached;

    protected virtual void OnThresholdReached(EventArgs e)
    {
        EventHandler handler = ThresholdReached; // <-- (*)
        handler?.Invoke(this, e);
    }

    // provide remaining implementation for the class
}

You can find it here: https://docs.microsoft.com/en-us/dotnet/standard/events/

Whats the motivation behind the instantiation at (*), why not just write:

class Counter
{
    public event EventHandler ThresholdReached;

    protected virtual void OnThresholdReached(EventArgs e)
    {
        ThresholdReached?.Invoke(this, e);
    }
}

CodePudding user response:

There's no difference. Maybe the author wanted to demonstrate that you can assign an event handler to a variable, but you can shorten the code like you proposed without any consequences.

  • Related