0

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.

  • 1
    "I just removed all the smoke detectors from the house and everything in it kept working as it did before, so I guess smoke detectors are unnecessary". No: everything *except the smoke detectors* worked as before. When you remove a safety system that safety system no longer operates. – Eric Lippert Feb 06 '14 at 13:41
  • @EricLippert: Nice analogy. Made sense. – now he who must not be named. Feb 06 '14 at 15:43

5 Answers5

1

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.

Adil
  • 146,340
  • 25
  • 209
  • 204
1

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.

BitExodus
  • 749
  • 6
  • 10
1

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.

Grzenio
  • 35,875
  • 47
  • 158
  • 240
1

'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.

Sameer
  • 2,143
  • 1
  • 16
  • 22
1

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);
}
Community
  • 1
  • 1
Maarten
  • 22,527
  • 3
  • 47
  • 68