Raising events safely means making sure your program does not crash when notifying others about something that happened.
Raising events safely in C Sharp (C#)
EventHandler? handler = EventName; if (handler != null) { handler(this, EventArgs.Empty); }
Copy the event delegate to a local variable before checking for null and invoking it.
This prevents errors if the event handlers change while the event is being raised.
MyEvent.EventHandler? handler = MyEvent; if (handler != null) { handler(this, EventArgs.Empty); }
MyEvent?.Invoke(this, EventArgs.Empty);This program defines an event and raises it safely by copying the event delegate to a local variable before invoking it. It prints a message when the event is raised.
using System; class Program { public event EventHandler? MyEvent; public void RaiseMyEvent() { EventHandler? handler = MyEvent; if (handler != null) { handler(this, EventArgs.Empty); } } static void Main() { Program p = new Program(); p.MyEvent += (sender, e) => Console.WriteLine("Event was raised safely!"); p.RaiseMyEvent(); } }
Always copy the event delegate to a local variable before checking for null and invoking it.
Using the null-conditional operator ?.Invoke is a modern and concise way to raise events safely.
Raising events safely helps avoid race conditions and null reference errors.
Raising events safely prevents errors when no handlers are attached.
Copy the event delegate to a local variable before invoking it.
Use ?.Invoke for a shorter safe event call.