In my class I want to declare an event that other classes can subscribe to. What is the correct way to declare the event?
This doesn't work:
public event CollectMapsReportingComplete;
Use the += operator to associate an event with an instance of a delegate that already exists. In C#, events may be raised by just calling them by name similar to method invocation, say MyEvent(10).
Use "event" keyword with delegate type variable to declare an event. Use built-in delegate EventHandler or EventHandler<TEventArgs> for common events. The publisher class raises an event, and the subscriber class registers for an event and provides the event-handler method.
Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.
In C# 6.0 and above you can use Null Propagation: handler?. Invoke(this, e); handler(this, e) will call every registered event listener.
You forgot to mention the type. For really simple events, EventHandler
might be enough:
public event EventHandler CollectMapsReportingComplete;
Sometimes you will want to declare your own delegate type to be used for your events, allowing you to use a custom type for the EventArgs
parameter (see Adam Robinson's comment):
public delegate void CollectEventHandler(object source, MapEventArgs args); public class MapEventArgs : EventArgs { public IEnumerable<Map> Maps { get; set; } }
You can also use the generic EventHandler
type instead of declaring your own types:
public event EventHandler<MapEventArgs> CollectMapsReportingComplete;
You need to specify the delegate type the event:
public event Action CollectMapsReportingComplete;
Here I have used System.Action
but you can use any delegate type you wish (even a custom delegate). An instance of the delegate type you specify will be used as the backing field for the event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With