Introduction
C# has provides event driven programming by adding support through Events. It is a way to provide notifications to client when something happens to an object. It is an encapsulation of idea that "Something happened". Events and Delegates are tightly coupled concept because event handling requires Delegate for the dispatch of Event.
The class that send or raises the event is called "Publisher" and class that receives or handle the event is called "Subscriber".
Below is the UML - Class Diagram of "Publisher-Subscriber" or Event Driven concepts:
Below are the key points about Events:
Following are the key points about Event:
- Event Handlers in C# return void and take two parameters.
- The First parameter of Event - Source of Event means publishing object.
- The Second parameter of Event - Object derived from EventArgs.
- The publishers determines when an event is raised and the subscriber determines what action is taken in response.
- An Event can have so many subscribers.
- Events are basically used for the single user action like button click.
- If an Event has multiple subscribers then event handlers are invoked synchronously.
Syntax for the declaration of Event:
- public event EventHandler MyEvent;
Steps for implementing Event:
To declare an event inside a class, first a Delegate type for the Event must be declared like below:
- public delegate void MyEventHandler(object sender, EventArgs e);
Declare Event:
- public event MyEventHandler MyEvent;
Invoking an Event:
- if (MyEvent != null) MyEvent(this, e);
Invoking an Event can only be done from within the class that declared the Event.
Hooking up Event:
- MyEventClass.MyEvent += new ChangedEventHandler(MyEventChanged);
Now, Detach the event: - MyEventClass.MyEvent -= new ChangedEventHandler(MyEventChanged);
Add/Remove Operation in Events
Below is the example of an Event -
System.EventHandler Delegate type:
- public class MyTest
- {
- public event EventHandler MyEvent
- {
- add
- {
- Console.WriteLine("add operation");
- }
- remove
- {
- Console.WriteLine("remove operation");
- }
- }
- }
- public class Test
- {
- public void TestEvent()
- {
- MyTest myTest = new MyTest();
- myTest.MyEvent += myTest_MyEvent;
- myTest.MyEvent -= myTest_MyEvent;
- }
- public void myTest_MyEvent(object sender, EventArgs e)
- {
- }
- }
- static void Main(string[] args)
- {
- Test test = new Test();
- test.TestEvent();
- Console.ReadKey();
- }
Output:
add operation
remove operation
Event - Basic Conceptual Implementation
Below implementation will show message whenever new item into ArrayList will be added.
- public delegate void EventHandler(object sender, EventArgs e);
- public class Publisher: ArrayList
- {
- public event EventHandler ProdcutAddedInfo;
- protected virtual void OnChanged(EventArgs e)
- {
- if (ProdcutAddedInfo != null) ProdcutAddedInfo(this, e);
- }
- public override int Add(Object product)
- {
- int added = base.Add(product);
- OnChanged(EventArgs.Empty);
- return added;
- }
- public override void Clear()
- {
- base.Clear();
- OnChanged(EventArgs.Empty);
- }
- public override object this[int index]
- {
- set
- {
- base[index] = value;
- OnChanged(EventArgs.Empty);
- }
- }
- }
Now,
- public class Subscriber
- {
- private Publisher publishers;
- public Subscriber(Publisher publisher)
- {
- this.publishers = publisher;
- publishers.ProdcutAddedInfo += publishers_ProdcutAddedInfo;
- }
- void publishers_ProdcutAddedInfo(object sender, EventArgs e)
- {
- if (sender == null)
- {
- Console.WriteLine("No New Product Added.");
- return;
- }
- Console.WriteLine("A New Prodct Added.");
- }
- public void UnSubscribeEvent()
- {
- publishers.ProdcutAddedInfo -= publishers_ProdcutAddedInfo;
- }
- }
Execute Code: - class Program
- {
- static void Main(string[] args)
- {
- Publisher publisher = new Publisher();
- Subscriber subscriber = new Subscriber(publisher);
- publisher.Add(new Product
- {
- ProductName = "Complan", Price = 20
- });
- publisher.Add(new Product
- {
- ProductName = "Horlics", Price = 120
- });
- publisher.Add(new Product
- {
- ProductName = "Boost", Price = 200
- });
- subscriber.UnSubscribeEvent();
- Console.ReadKey();
- }
- }
Output: A New Product Added.
A New Product Added.
A New Product Added. Question: Can we use Events without Delegate?
Answer: No, Events use Delegates internally. Events are encapsulation over Delegates. There is already defined Delegate "EventHandler" that can be used like below:
- public event EventHandler MyEvents;
So, it also used Delegate Internally.
I have attached sample code. Read and debug the code very carefully so you will understand the concept of Event in C#.