Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET event raising and NullObject pattern

We can raise event in two ways:

public event EventHandler MyEvent;

private void DoSomething()
{
    ...
    var handler = MyEvent;
    if (handler != null)
        handler(this,EventArgs.Empty);
}

and

public event EventHandler MyEvent = (o,e) => {} ;

private void DoSomething()
{
    ...
    MyEvent(this, EventArgs.Empty);
}

I prefer the last one. It is shorter.
My colleagues insist on the first variant.

Is there any superiority of the first over the second one?

like image 380
Pavel Voronin Avatar asked Nov 29 '12 15:11

Pavel Voronin


1 Answers

Update for C# 6

In C# 6 you simply use the null-conditional operator like so:

PropertyChanged?.Invoke(this, args);

This is recommended by the Roslyn wiki

Original Answer

Eric Lippert has a great blog post on Events and Races, which you should read if you haven't.

The first option could be considered safer than the second because the event could get set to null. Someone could carelessly modify the class. Also, if you deserialize instances the 2nd method won't work (depending on the serialization mechanism you use).

I sometimes use a helper method to raise events

static class Raiser
{
    public static void Raise<T>(this EventHandler<T> evnt, object sender, T args)
        where T : EventArgs
    {
        if (evnt != null)
        {
            evnt(sender, args);
        }
    }
}

class SomeClass
{
    public event EventHandler<EventArgs> MyEvent;

    private void DoSomething()
    {
        MyEvent.Raise(this, EventArgs.Empty);
    }
}
like image 81
default.kramer Avatar answered Oct 13 '22 23:10

default.kramer