Initialization of events against checking for zero

It was mostly in my head for a while ... and I would like to read your opinion

I read a great book from Jon Skeet, calling it: C # in Depth, Second Edition, and it is recommended that you use something like this when declaring custom events:

public event Action<string> MyEvent = delegate { };

This declaration will free us from the validation statement before the event fires, so instead:

    if (this.MyEvent != null)
    {
        this.MyEvent("OMG osh");
    }

We can simply call:

this.MyEvent("OMG osh");

And our code will just work.

When you declare such events, the event will be triggered by an empty delegate, so we do not need to check for null.

This is another way to declare events, they are equivalent

private Action<string> myDelegate;
public event Action<string> MyEvent
{
    add
    {
        this.myDelegate += value;
    }
    remove
    {
        this.myDelegate -= value;
    }
}

For more information: http://csharpindepth.com/Articles/Chapter2/Events.aspx

, , , , , , null , , . , , ,

  • , - (, ) , ,

  • patter, if, . ?

+5
2

-: , ? , null ? , .

, : , , null , , , , , , Jon Skeet delegate { } .

, , / (, SynchronizationContext) . , , (, SynchronizationContext.Post).

null, , :

if (this.MyEvent != null)
{
    this.MyEvent("OMG osh");
}

:

Action<string> handlers = this.MyEvent;
if (handlers != null)
{
    handlers("OMG osh");
}

. , . ( , , - .)


: , :

[W], , , , delegate event.

, , CLI (, add, remove, raise , , ). . , # , , , (.. += -=), , ).

+1

, . , , , : ", , - "

, , , , .

, ( )

Action on EventHandler, , .

public static class ActionExtension
{
    public static void SafeInvoke<T>(this Action<T> action, T arg)
    {
        var temp = action;
        if (temp != null)
        {
            temp(arg);
        }
    }
}

public event Action<string> InterestingEvent;
// event invoker
InterestingEvent.SaveInvoke("Boo!");
+3
source

All Articles