Why is the "EventHandler cccc public event" null?

Why is "public event EventHandler cccc" null?

I have a class that

public class Builder
{
    public event EventHandler StartedWorking;

    public Builder()
    { 
        // Constructor does some stuff
    }

    public void Start()
    {
       StartedWorking(this, eventargobject); //StartedWorking is null --
    }
}   

Does it seem simple and something that I do all the time? Am I missing something obvious or is there something that can cause this?

EDIT:

Does this mean that if I fire an event that is not signed in the client class, I have to check that it is not null?

EDIT-2:

I think I have never had events that never signed and therefore never came across this - you learn something new every day. Sorry for the seemingly stupid question ....

+3
source share
4 answers

null, - . , .

:

public void Start()
{
    var handler = this.StartedWorking;
    if (handler != null)
    {
         handler(this, eventArgObject);
    }
}

, .

+11

, , .

: , null, . , if(StartedWorking != null){...}, , , . - null:

protected void OnStartedWorking()
{
    EventHandler localEvent = StartedWorking
    if(localEvent != null)
    {
        localEvent(this, EventArgs.Empty);
    }
}

, , .

MSDN: , .NET Framework

( , .net MultiCastDelegate imutable, , )

+2

- StartedWorking, null. .NET.

This article , among other things, shows that you must check null before invoking an event. This other question and answer shows how you can create events in such a way as to avoid null checking (mainly by adding an empty handler always).

0
source

You do not need to assign a function?

StartedWorking += new EventHandler(afunction);

void afunction(object sender, EventArgs e)
{
   DoSomething();
}
0
source

Source: https://habr.com/ru/post/1750562/


All Articles