Search code examples
c#.netevents

Why would a 'public event EventHandler cccc' be null?


Why would a 'public event EventHandler cccc' be null?

I have a class that's

public class Builder
{
    public event EventHandler StartedWorking;

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

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

This seems straightforward and something I do all the time? Am I missing something obvious or is there something that could cause this?

EDIT:

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

EDIT-2:

I guess I'd never had events that were never not subscribed to and hence never ran into this -- You learn something new every day Sorry about the seemingly stupid question....


Solution

  • The event handler will be null unless somebody has subscribed to the event. As soon as a delegate is subscribed to the event, it will no longer be null.

    This is why it's always suggested to use the following form for raising events:

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

    This protects you from a null exception if there has been no subscribers.