The following example shows how to declare and raise an event that uses EventHandler as the underlying delegate type. For the complete code example that also shows how to use the generic EventHandler<TEventArgs> delegate type and how to subscribe to an event and create an event handler method, see How to: Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide).
public class SampleEventArgs
{
public SampleEventArgs(string s) { Text = s; }
public String Text {get; private set;} // readonly
}
public class Publisher
{
// Declare the delegate (if using non-generic pattern).
public delegate void SampleEventHandler(object sender, SampleEventArgs e);
// Declare the event.
public event SampleEventHandler SampleEvent;
// Wrap the event in a protected virtual method
// to enable derived classes to raise the event.
protected virtual void RaiseSampleEvent()
{
// Raise the event by using the () operator.
if (SampleEvent != null)
SampleEvent(this, new SampleEventArgs("Hello"));
}
}
Events are a special kind of multicast delegate that can only be invoked from within the class or struct where they are declared (the publisher class). If other classes or structs subscribe to the event, their event handler methods will be called when the publisher class raises the event. For more information and code examples, see Events (C# Programming Guide) and Delegates (C# Programming Guide).
Events can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the event. For more information, see Access Modifiers (C# Programming Guide).