An event is a member that enables an object to trigger notifications. Event users can attach executable code for events by supplying event handlers. The event keyword declares an event. The event is of a delegate type. While an object triggers an event, the event invokes all supplied event handlers. Event handlers are delegate instances added to the event and executed when the event is raised. Event users can add or remove their event handlers on an event.
publicclassSampleEventArgs
{
publicSampleEventArgs(string text) { Text = text; }
publicstring Text { get; } // readonly
}
publicclassPublisher
{
// Declare the delegate (if using non-generic pattern).publicdelegatevoidSampleEventHandler(object sender, SampleEventArgs e);
// Declare the event.publicevent SampleEventHandler SampleEvent;
// Wrap the event in a protected virtual method// to enable derived classes to raise the event.protectedvirtualvoidRaiseSampleEvent()
{
// Raise the event in a thread-safe manner using the ?. operator.
SampleEvent?.Invoke(this, new SampleEventArgs("Hello"));
}
}
Events are a special kind of multicast delegate that can only be invoked from within the class (or derived classes) 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 and Delegates.
The compiler will not generate the add and remove event accessor blocks and therefore derived classes must provide their own implementation.
An event may be declared as a static event by using the static keyword. This makes the event available to callers at any time, even if no instance of the class exists. For more information, see Static Classes and Static Class Members.
An event can be marked as a virtual event by using the virtual keyword. This enables derived classes to override the event behavior by using the override keyword. For more information, see Inheritance. An event overriding a virtual event can also be sealed, which specifies that for derived classes it is no longer virtual. Lastly, an event can be declared abstract, which means that the compiler will not generate the add and remove event accessor blocks. Therefore derived classes must provide their own implementation.
C# language specification
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.