Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the syntax to declare an event in C#?

Tags:

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; 
like image 572
Tilendor Avatar asked Mar 17 '10 18:03

Tilendor


People also ask

What is correct syntax of event in C#?

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

How do you declare an event variable in C#?

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.

What do you mean by event in C?

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.

How do you call an event handler in C#?

In C# 6.0 and above you can use Null Propagation: handler?. Invoke(this, e); handler(this, e) will call every registered event listener.


2 Answers

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; 
like image 74
Jørn Schou-Rode Avatar answered Jan 02 '23 05:01

Jørn Schou-Rode


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.

like image 36
Andrew Hare Avatar answered Jan 02 '23 04:01

Andrew Hare