Tilendor
Tilendor

Reputation: 48903

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

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;

Upvotes: 29

Views: 29313

Answers (5)

Jørn Schou-Rode
Jørn Schou-Rode

Reputation: 38346

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;

Upvotes: 38

tsinik
tsinik

Reputation: 503

public event [DelegateType] [EventName];

Upvotes: 1

galford13x
galford13x

Reputation: 2531

An Example

/// </summary>
/// Event triggered when a search is entered in any <see cref="SearchPanel"/>
/// </summary>
public event EventHandler<string> SearchEntered
{
    add { searchevent += value; }
    remove { searchevent -= value; }
}
private event EventHandler<string> searchevent;

Upvotes: 3

Josh
Josh

Reputation: 44906

public event EventHandler MyEvent;

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351476

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.

Upvotes: 8

Related Questions