Events allow us two things:

  1. If something important has occurred object notifies its subscribers about that occurrence.
  2. Objects that listen to another object are notified about changes of that object.

To declare event, you use event keyword followed by the type of delegate for the event, meaning we have to declare delegate before we can use event.

Typically, to raise an event, you would use protected void method. Name of that method by convention goes should be like this: OnEventName. Method should raise eventĀ  and provide two parameters object and EventArgs. Delegate upon whose type event uses should have two parameters: Object parameter is usually named sender and EventArgs parameter is named args. sender parameter is the source of the event. You should use EventArgs if you do not intend to send any parameters to subscriber, if on the other hand you wish to supply parameters create an class that inherits from from EventArgs and use that class as an parameter.

Example:

Lets create an application that is used to insert an employee to database. Upon inserting and after inserting few people should be notified, meaning we will have two events.

  • First, when we start inserting employee in database, we will notify our System Administrator that process of inserting has started. Also we will provide Sys Admin with DateTime value which will represent time when insert operation has started.
  • Second, after employee has been inserted in database, CEO, Website and System Admin will be notified.

You can also download entire solution for easier readability.

If you prefer using Action delegate instead of declaring delegates you can easily doe that. Just replace following code in HRDepartment class:

For now we will finish our journey with Delegates and return to Reflection.