Do I need to register someone at an event before you can pick it up?

It sounds crazy, but I created an event in the class and tried to raise it without pointing to it. However, this will give an exception. Does anyone need to register with him before he makes an exception? If so, what is the work around?

+4
source share
7 answers

yes, an event that is not registered on it is null. The standard way to fire:

event EventHandler MyEvent; private void FireMyEvent(EventArgs e) { var handler = MyEvent; if (handler != null) handler(this, e); } 

Eric Lippert wrote a fantastic article on why this template is the β€œright” way to trigger events.

+14
source

Yes. If there are no subscribers, the event will be empty and you will get a NullReferenceException when it is called. The right way to do the verification, as thecoop said, but there is a simple "shortcut":

 public event EventHandler Event = delegate {}; 

This causes the event to have a default subscriber that does nothing, and therefore will not throw an exception if there are subscribers. There is little overhead for this, but it eliminates the need to check for zeros.

+5
source

In .NET, events (by default) are handled as multicast delegates. This means that until you assign the first event handler to the event, the event reference will be evaluated as null .

This led to a typical way to raise an event:

 public event EventHandler Event; protected virtual void OnEvent(EventArgs e) { EventHandler @event = Event; // Copy immutable delegate for thread safety. if(@event != null) // Check for null. @event(e); // Raise event. } 
+3
source

Check null value.

 if (Object.Event != null) Object.Event(); 

NTN Alex

+1
source

If no one has subscribed to the event, the event object is null . The OnEvent -like method is usually used (for example, if your event is called MyEvent ):

 public event EventHandler<MyEventArgs> MyEvent; void OnMyEvent(MyEventArgs args) { if(MyEvent != null) MyEvent(this, args); } 

When you need to raise an event, you simply call the OnMyEvent method.

+1
source

Just to add, you can also use extension methods.

  public static void RaiseSafe<T>(this EventHandler<T> eventHandler, object sender, T args) where T : EventArgs { if (eventHandler != null) eventHandler(sender, args); } 

And use it as follows:

 MyEvent.RaiseSafe(this,new EventArgs()); 
+1
source

The simplest solution to this problem is to declare an event:

 public event EventHandlerType MyEvent = delegate { }; 

In other words, add = delegate { }; In the end.

Now you do not need to write a load of garbage every time you raise an event.

0
source

All Articles