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;
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;
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.
The other answers are good. However, there's a good tutorial here if you need more in-depth information.
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;