Why is an additional if statement to check if an event is null before invoking it?

I am going through this code below:

public delegate void PersonArrivedEventHandler(string personName, byte[] personId);

    public class SCLib
    {
        public event personArrivedEventHandler personrrived;

        public SCLib()
        {
            // Simulate that the person arrived after 2000 milli-seconds.
            Task.Run(() =>
            {
                System.Threading.Thread.Sleep(2000);
                OnPersonArrived("personName", new byte[] { 0x20, 0x21, 0x22 });
            });
        }

        protected virtual void OnPersonArrived(string smartCardReaderName, byte[] smartCardId)
        {
            if (this.personArrived != null)
            {
                PersonArrived(personName, personId);
            }
        }
    }

But, I don't know what is the significance of this line, if (this.personArrived != null).

Why is this check done here? Is there any significance of the if statement here? I removed this line and ran the program and everything works as before.

Thanks.

Upvotes: 0

Views: 109

Answers (5)

Maarten
Maarten

Reputation: 22955

In a multi-threading application you should store the eventhandlers in a local variable before invoking. See this SO answer, this blog post from Eric Lippert and this SO answer for more details.

void SomeEventInvoke(object sender, EventArgs args) {
    EventHandler ev = SomeEvent;
    if (ev != null) ev(sender, args);
}

Upvotes: 1

Sameer
Sameer

Reputation: 2171

'Events' are subscribe by class object using add handler.

SCLibObject.personrrived += new personArrivedEventHandler(somemethod)

If class object is not subscribe the event then you will get NullReferenceException. So before calling events check if it is null or not.

Upvotes: 1

Grzenio
Grzenio

Reputation: 36679

Because it will be null if no delegates are attached to the event. If you try to invoke such a null event you will get the standard NullReferenceException.

Upvotes: 1

BitExodus
BitExodus

Reputation: 747

If you use an event which you have not assign a handler it will generate an exception because it is null, so you need to check it before launch the event.

Upvotes: 1

Adil
Adil

Reputation: 148160

If the event is not subscribed by the consumer of the class then invoking the event would raise exception as PersonArrived is null if not subscribed.

Upvotes: 1

Related Questions