Note: Before start reading this article please hold a clear concept on delegates. Follow the link to read the previous article on Delegates.
What is Event?
- Event is a way to communicate in-between objects, which send notification to its subscribers (who register for that Event).
- Events are declared with an associated delegate.
- We know previously that delegate hold a reference to a method.
- Events sender send notification that’s how event raised and receiver receive the notifications.
- We can extends application by adding new methods without changing existing code.
- To build loosely coupled applications.
- The class containing the event is used to publish the event, called Publisher/Sender.
- Containing information’s about the event known as event arguments.
- The class accepts this event is called the Subscriber/Receiver.
- The method that execute by publisher call is known as event handlers.
Diagram of Event Sender and Receiver
Let’s demonstrate with a sample example:
- namespace Events
- {
- class Program
- {
- static void Main(string[] args)
- {
- IQTest objTest = new IQTest();
- NotificationService objNotify = new NotificationService();
-
-
- objTest.ExamStarted += objNotify.OnExamStarted;
-
- objTest.myExam();
- Console.Read();
- }
- }
-
-
- class IQTest
- {
-
- public delegate void ExamEventHandler(object source, EventArgs args);
-
-
- public event ExamEventHandler ExamStarted;
-
- public void myExam()
- {
- Console.WriteLine("Exam is Starting..");
- Thread.Sleep(2000);
- OnExamStarted();
- }
-
-
- protected virtual void OnExamStarted()
- {
-
- if (ExamStarted != null)
- {
- ExamStarted(this, EventArgs.Empty);
- }
- }
- }
-
-
- class NotificationService
- {
-
- public void OnExamStarted(object source, EventArgs args)
- {
- Console.WriteLine("Your time starts now | start answering..");
- }
- }
- }
Output:Exam is Starting..
Your Time starts now | start answering.. Let’s consider the code step by step:In this code the publisher is IQTest class, there is a method named OnExamStarted that notifies the attended exam students that the exam is started. Steps of an Event Sender: - Define a Delegate
- Define an event based on that Delegate.
- Raise/Publish the event
Point 1: Define a Delegates
As we can see here to define a delegate is similar as method declaration as we saw in the previous article on Delegates.
-
- public delegate void ExamEventHandler(object source, EventArgs args);
As we know delegate points a method. Here delegate respond between Publisher/Sender and Subscriber/Receiver. Establish the event handler method. Point 2: Define an event
-
- public event ExamEventHandler ExamStarted;
An event is declared based on the associated Delegates.
Button click, Text change of a textbox are known as event. Those are generally seen in windows form application. Point 3: Publish the eventTo publish an event we need to check that event is null or not. This method is responsible for notifying all the subscribers.
- protected virtual void OnExamStarted()
- {
-
- if (ExamStarted != null)
- {
- ExamStarted(this, EventArgs.Empty);
- }
- }
Here we can see that there are two parameters passed in ExamStarted method, the first parameter (this) which is for the source of the event (current objects) and the second one is to send additional data with that event (this time it’s empty). Register a Handler for that Event:
This is done with += operators. We can also have multiple functions registering for the same event; all registered functions are called one by one.
- objTest.ExamStarted += objNotify.OnExamStarted;
If we want to remove any function, the -= operator is used.
- objTest.ExamStarted -= objNotify.OnExamStarted;
Example of Sending Event ArgumentsLet’s modify the previous example, this time we will add a new class called ExamEventArgs which has a property named examTime. The class ExamEventArgs is inheriting from EventArgs.
- public class ExamEventArgs : EventArgs
- {
- public int examTime { get; set; }
- }
And instead of Empty arguments
- ExamStarted(this, EventArgs.Empty);
We are using a new instance of ExamEventArgs with initializing time to 10.
- ExamStarted(this, new ExamEventArgs
- {
- examTime = 10
- });
Finally Merged sample Example:
- namespace Events
- {
- public class ExamEventArgs : EventArgs
- {
- public int examTime { get; set; }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- IQTest objTest = new IQTest();
- NotificationService objNotify = new NotificationService();
-
-
- objTest.ExamStarted += objNotify.OnExamStarted;
-
- objTest.myExam();
- Console.Read();
- }
- }
-
-
- class IQTest
- {
-
- public delegate void ExamEventHandler(object source, ExamEventArgs args);
-
-
- public event ExamEventHandler ExamStarted;
-
- public void myExam()
- {
- Console.WriteLine("Exam is Starting..");
- Thread.Sleep(2000);
- OnExamStarted();
- }
-
-
- protected virtual void OnExamStarted()
- {
-
- if (ExamStarted != null)
- {
- ExamStarted(this, new ExamEventArgs
- {
- examTime = 10
- });
- }
- }
- }
-
-
- class NotificationService
- {
-
- public void OnExamStarted(object source, ExamEventArgs e)
- {
- Console.WriteLine("Your Time starts now | start answering..");
- Console.WriteLine("Exam Start Time: " + e.examTime);
- }
- }
- }
Output: Exam is Starting..Your Time starts now | start answering..Exam Start Time: 10
Types of Event Handler:
There are two forms of event handler one is Normal form and one is Generic form. Here they are:
- Normal Form. - EventHandler
- Generic Form. - EventHandler<T>
Our previous example was with normal form of EventHandler.
Instead of creating our own we can use this Generic form. Let’s modify the previous example instead of using our own custom delegate
-
- public delegate void ExamEventHandler(object source, ExamEventArgs args);
-
-
- public event ExamEventHandler ExamStarted;
We can use a single line of code, and the output will be the same as previous.
-
- public event EventHandler<ExamEventArgs> ExamStarted;
Finally sample Example:- namespace Events
- {
- public class ExamEventArgs : EventArgs
- {
- public int examTime { get; set; }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- IQTest objTest = new IQTest();
- NotificationService objNotify = new NotificationService();
-
-
- objTest.ExamStarted += objNotify.OnExamStarted;
-
- objTest.myExam();
- Console.Read();
- }
- }
-
-
- class IQTest
- {
-
- public event EventHandler<ExamEventArgs> ExamStarted;
- public void myExam()
- {
- Console.WriteLine("Exam is Starting..");
- Thread.Sleep(2000);
- OnExamStarted();
- }
-
-
- protected virtual void OnExamStarted()
- {
-
- if (ExamStarted != null)
- {
- ExamStarted(this, new ExamEventArgs
- {
- examTime = 10
- });
- }
- }
- }
-
-
- class NotificationService
- {
-
- public void OnExamStarted(object source, ExamEventArgs e)
- {
- Console.WriteLine("Your Time starts now | start answering..");
- Console.WriteLine("Exam Start Time: " + e.examTime);
- }
- }
- }
Output:Exam is Starting..
Your Time starts now | start answering..
Exam Start Time: 10
Overview: - Events are implemented with delegates.
- Events communicate in-between of objects.
- A method that handles an event is called an event handler.
- To build loosely coupled applications events are helpful.
- We can extend application by adding new methods without changing other parts of the code.