The event keyword is used to declare an event in the publisher class.
The following example demonstrates how to declare and trigger events that use eventhandler as the basic delegate type.
Public ClassPublisher
{
// declare the delegate (if using non-generic pattern ).
Public Delegate VoidSampleeventhandler (ObjectSender, sampleeventargs E );
// Declare the event.
Public EventSampleeventhandler sampleevent;
// Wrap the event in a protected virtual Method
// to enable Derived classes to raise the event.
Protected Virtual VoidRaisesampleevent ()
{
// raise the event by using the () operator.
Sampleevent (This,NewSampleeventargs ("Hello"));
}
}
An event is a special type of multi-channel broadcast delegate and can only be called from the class or structure (publisher class) that declares them. If other classes or structures subscribe to this event, when the issuer class raises this event, it calls its event processing.ProgramMethod.
Events can be marked as public, private, protected, internal, or protected internal. These access modifiers define the way users access events of the class.
The following keywords can be applied to events.
Keywords |
Description |
Static |
The caller can use the event at any time even if the class does not have an instance. |
Virtual |
Allows a derived class to override event behavior by using the override keyword. |
Sealed |
Specifies that it is no longer virtual for a derived class. |
Abstract |
The compiler does not generate add and remove event accessors. Therefore, the derived class must provide its own implementation. |
You can declare an event as a static event by using the static keyword. Even if the class does not have any instances, the caller can use static events at any time. You can use the virtual keyword to mark an event as a virtual event. In this way, the derived class can override event behavior by using the override keyword. The event that overrides virtual events can also be sealed to indicate that it is no longer a virtual event for a derived class. Finally, the event can be declared as abstract, which means that the compiler will not generate add and remove event accessors. Therefore, the derived class must provide its own implementation.