Freigeben über


Raising an Event 

Event functionality is provided by three interrelated elements: a class that provides event data, an event delegate, and the class that raises the event. The .NET Framework has a convention for naming classes and methods related to events. If you want your class to raise an event named EventName, you need the following elements:

  • A class that holds event data, named EventNameEventArgs. This class must derive from System.EventArgs.

  • A delegate for the event, named EventNameEventHandler.

  • A class that raises the event. This class must provide the event declaration (EventName) and a method that raises the event (OnEventName).

The event data class and the event delegate class might already be defined in the .NET Framework class library or in a third-party class library. In that case, you do not have to define those classes. For example, if your event does not use custom data, you can use System.EventArgs for your event data and System.EventHandler for your delegate.

You define an event member in your class using the event keyword. When the compiler encounters an event keyword in your class, it creates a private member such as:

private EventNameHandler eh = null;

The compiler also creates the two public methods add_EventName and remove_EventName. These methods are event hooks that allow delegates to be combined or removed from the event delegate eh. The details are hidden from the programmer.

NoteNote

In languages other than C# and Visual Basic 2005, the compiler might not automatically generate the code corresponding to an event member, and you might have to explicitly define the event hooks and the private delegate field.

Once you have defined your event implementation, you must determine when to raise the event. You raise the event by calling the protected OnEventName method in the class that defined the event, or in a derived class. The OnEventName method raises the event by invoking the delegates, passing in any event-specific data. The delegate methods for the event can perform actions for the event or process the event-specific data.

NoteNote

The protected OnEventName method also allows derived classes to override the event without attaching a delegate to it. A derived class must always call the OnEventName method of the base class to ensure that registered delegates receive the event.

When you want to handle events raised in another class, you add delegate methods to the event. If you are not familiar with the delegate model for events in the .NET Framework, see Events and Delegates.

See Also

Tasks

How to: Raise and Consume Events
How to: Implement Events in Your Class

Concepts

Events and Delegates

Other Resources

Handling and Raising Events