C # and Lambdas events, an alternative to null checking?

Anyone see the flaws? It should be noted that you cannot remove anonymous methods from the list of event delegates, I know about it (in fact, it was a conceptual motivation for this).

The goal here is an alternative:

if (onFoo != null) onFoo.Invoke(this, null);

And the code:

public delegate void FooDelegate(object sender, EventArgs e);

public class EventTest
{
    public EventTest()
    {
        onFoo += (p,q) => { };
    }

    public FireFoo()
    {
         onFoo.Invoke(this, null);
    }

    public event FooDelegate onFoo;

}

+5
source share
3 answers
public event FooDelegate onFoo = delegate {};
+3
source

One option is to use the extension method instead:

public static class EventExtensions {
    public static void Fire<T>(this EventHandler<EventArgs<T>> handler, object sender, T args) {
        if (handler != null)
            handler(sender, new EventArgs<T>(args));
    }
}

Now it is simple:

TimeExpired.Fire(this, new EventArgs());
+5
source

In the latest versions of Visual Studio, it is automatically proposed to use a null-condition operator :

onFoo?.Invoke(this, null);

(whenever this type of code is encountered :) if (onFoo != null) onFoo.Invoke(this, null).

This operator became available with the release of C # 6.0 in 2015.

0
source