How to Implement Events In C#

C# supports event-driven programming via delegates. Delegates and events notify client applications when some state changes an object. It is an encapsulation of the idea that "Something happened". Events and Delegates are tightly coupled concepts because event handling requires delegate implementation to dispatch events.

The class that sends or raises an event is called a Publisher, and the class that receives or handles the event is called a "Subscriber". 

Below is the UML - Class Diagram of "Publisher-Subscriber" or Event Driven concepts:

UML - Class Diagram

Below are the key points about C# Events

Following are the key points about events in C#: 

  1. Event Handlers in C# return void and take two parameters.
  2. The First parameter of Event - Source of Event means publishing the object.
  3. The Second parameter of Event - Object derived from EventArgs.
  4. The publisher determines when an event is raised, and the subscriber determines what action is taken in response.
  5. An Event can have so many subscribers.
  6. Events are used for single user action like button click.
  7. If an Event has multiple subscribers, then event handlers are invoked synchronously.

The syntax for the declaration of an 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 an 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 an 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 a message whenever a new item into ArrayList is 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#.
 
Learn next 
 
Here is a detailed tutorial on Delegates and Events in C#
 


Similar Articles