If your event should not contain any additional information (Foo is the name of your event):
public event EventHandler Foo;
And lift it like this:
protected virtual void OnFoo() { if (Foo != null) Foo(this, EventArgs.Empty); }
If you need to pass some additional information to event handlers, then create your own argument class, inheriting from EvenArgs
class
public class FooEventArgs : EventArgs { public string Message { get; private set; } public FooEventArgs(string message) { Message = message; } }
Declare an event this way:
public event EventHandler<FooEventArgs> Foo;
And lift it like this:
protected virtual void OnFoo(string message) { if (Foo != null) Foo(this, new FooEventArgs(message)); }
It is good practice to create protected methods for creating events by descendants of the class where the event is declared. It is also recommended that you use the event naming convention:
- add the
-ing
suffix to the event name for events that were raised before something happened (often you can cancel such events) (for example, checking) - add
-ed
suffix to the event name for events that occurred after something happened (for example, clicked)
As Torsten said, itβs good practice to create virtual
methods for raising events. This not only allows you to raise events from descendants, but also disable event creation, or add some behavior before / after the event.
source share