Updated date:

C# Custom Events Explained With Example

Author:

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like video games and reading books.

1. Introduction to Events

An event is a kind of ‘Something Happened’. Some examples are the button got pressed; a check mark from the check box is removed. We all know, we call these kinds of action as Events.

So let us consider a form that has a button in it. We all know that a button can be clicked. The user does the action of clicking a button and we as code writer do not know when that action will happen. Now, let us say, we like to write a code which says, “Hello There” whenever a user clicks the button. So what we think now.

We will say, “Not a big deal. Double click the button, the Development Environment will bring us to a function, and write the code there which says “Hello There” to the user.

Well. the Team Lead (Yes, the same guy who always bugs us) asks you, “Hey! We have a Class called ProductStock, and it maintains the stock in hand in an integer variable. Can you expose an event say Low-Stock so that the client’s of our Class can provide a handler function to handle the situation their own way?”. This will end up thinking about exposing our own event in the ProductStock Class and the event is called “Custom Event”.

2. Publish and Subscribe

If we go back to the button click on the form that says “Hi there”, there are some piece of information we need to know.

  1. A Container can hold one or more Components. The button is placed on the form which is a Component. The form is a Container which holds the button.
  2. The Button class in dot net exposes an event called Click. So button class is the Publisher of the event click.
  3. The Form class wants to know when the button got clicked. So it subscribes for the published Click Event. We call the Form as a Subscriber of the Event.
  4. When the Button on the Form is clicked, it notify Subscriber of the Click Event. And there is an Event Handler code that says “Hi There”, when the notification is received.

So the publish is nothing but exposing the event and subscribe is a kind of getting the notification on the event handler function. Delegates and Events are tightly coupled. We will see how when we are writing our code example.

3. About The Example

In this example, we have two classes. One is the ProductStock class, which maintains the current stock of the product. The other class is Counter which is used by the Billing Counter computers in the retail shop. Let us say; the customer comes to any Billing Counter, informs the product he wants to purchase, pays the bill and goes to the storeroom to receive the product. Each Billing Counter receives a notification when the product stock goes low.

Consider the below picture before we move on:

Custom Events Publish and Subscribe

Custom Events Publish and Subscribe

The above picture explains the following:

  1. The ProductStock class publishes the event, LowStock.
  2. Purchase, Counter etc Classes subscribes to the Published event, LowStock.
  3. ProductStock sends the notification to the entire subscribers when the ProductStock goes low.

In our Example, we are not going to Implement Purchase Class and a Class named Someother.

4. The ProductStock Class - Event Publisher

1) The ProductStock has two member variables. One is to know the product name, and another one is to keep track of the current stock. The current stock is get reduced by the sales counter when a sale of the product is performed.

//001: The class maintains Current Stock of 
//the product. It publishes an LowStock 
//event. Sends Notifications to the 
//subscriber of the event when the product 
//stock goes lower than 5
public class ProductStock
{
	//001_1: Member Variable.
	public string ProductName;
	private int StockInHand;

2) This Class declares a Multicast Delegate called OnStockLow that takes an Event Source object and EventArgs object. The Event Source here is ProductStock as it will raise the Notification Event. EventArgs Class can pack the information related to the Event. To keep this example simple, we have derived no object from EventArgs. We declare the Multicast Delegate as shown below:

//001_2: Multicast delegate type that 
//get coupled with the event.
public delegate void OnStockLow(
  object sender, EventArgs e);

3) Next, we declare the StockLow Event. Note, how the Delegate is coupled with the Event. It implies that notification handler function should return void. In Addition, it must receive the object as a first parameter and EventArgs as the second parameter. As it is a Multicast Delegate, one can use Delegate Chain of above said functions. OK, Now the Product stock published the Event. Below is the declaration of the Event:

//001_3: Published event (StockLow), 
//that takes responsibility of sending 
//notification to the scbscriber through 
//the above Specified multicast delegate
public event OnStockLow StockLow;

Note the syntax:

public event <delegate type name> <event_name>.

4) The constructor of the ProductStock class initializes the members ProductName and StockInHand. Below is the code:

//001_4: Constructor that Initializes 
//the Stock
public ProductStock(string Name, 
  int OpeningStock)
{
	ProductName = Name;
	StockInHand = OpeningStock;
}

5) All the Counter objects call the ReduceStock function when a sale is performed. This function reduces the current stock. It also notifies the subscriber of the LowStock event when the current stock goes less than five. Below is the function implementation:

//001_5: This function reduces the stock 
//based on the sales on the billing 
//counters. When the stock in hand is 
//lower than 5, it raises the 
//StockLow event.
public void ReduceStock(int SalesDone)
{
	StockInHand = StockInHand - SalesDone;
	if (StockInHand < 5 )
	{
		EventArgs arg = new EventArgs();
		StockLow(this, arg);
	}
}

Note that in the above code, call to StockLow(this,arg) is known as Raising an Event or sending a Notification. We are done with the implementation ProductStock class.

5. The Counter Class - Event Subscriber

1) The counter class declares the member variable for the counter name and the constructor initializes the Name. The Sales function takes the ProductStock and the number of product sold. It makes a call to the ReduceStock function after counter make a sale. Below is the Implementation code:

//002: This class is for Sales Counter 
//that performs the Sales on different 
//counters and makes the billing. 
//This class Subscribes to the Published 
//event and Receives notification through 
//Multicast delegate.
public class Counter
{
	//002_1: Class member
	private string CounterName;

	//002_2: Constructor for Counter
	public Counter(string Name)
	{
		CounterName = Name;
	}

	//002_2: Function that records the sales 
        //performed on the billing desk
	public void Sales(ProductStock prod, 
    int howmuch)
	{
		Console.WriteLine(
      "{0} Sold {1} numbers", 
      prod.ProductName, 
      howmuch);
		prod.ReduceStock(howmuch);
	}

2) The counter class implements the notification handler for StockLow. We should note that the arguments and the void return type. Because this the rule which is expected by the delegate OnLowStock coupled with the event StockLow. Below is the handler:

//002_3: Function that acts as event 
//handler for LowStock to receive the 
//notification
public void LowStockHandler(
  object Sender, EventArgs e)
{
	Console.WriteLine("Anouncement " +
    "on {0}: Stock of Product {1}" +
    " gone Low",
		CounterName , 
    ((ProductStock) Sender).ProductName );
}

6. The Main Program - Client Code

Now, we will see how the client code works. Before that a small refresh on what we did. The ProductStock class exposes an event StockLow, and that event is coupled to OnStockLow Delegate. ReduceStock function raises the StockLow event when the product stock goes below five. The counter class implements the notification handler (LowStockHandler) to receive the notification. Where is the piece of code that links the LowStockHandler to the StockLow event? We link that in the client code which we will write in this section.

1) First, the client creates the two billing counter objects. Below is the code for billing counter:

class ProgramEntry
{
	[STAThread]
	static void Main(string[] args)
	{
		//Client 001: Create Billing Counters
		Counter billing_counter1 =
      new Counter("Jupiter");
		Counter billing_counter2 =
      new Counter("Saturn");

2) Next, we create three ProductStock objects. These products will be sold through two counters which we created in the previous step. Below is the code:

//Client 002: Create the Product Stocks
ProductStock prod1 = new ProductStock(
  "Godrej Fridge", 7 );
ProductStock prod2 = new ProductStock(
  "Sony CD Player", 6);
ProductStock prod3 = new ProductStock(
  "Sony DVD", 800);

3) Next, we subscribe to the Event LowStock published by the ProductStock class. We do this by creating a Delegate which points to the Notification handler function. Note, we already implemented the handler in the Counter Class and here we are just binding it to Event. Below is the code:

//Client 003: Couple the Event with 
//the Handler through the Delegate.
prod1.StockLow += 
  new ProductStock.OnStockLow(
  billing_counter1.LowStockHandler);
prod2.StockLow += 
  new ProductStock.OnStockLow(
  billing_counter1.LowStockHandler);
prod1.StockLow += 
  new ProductStock.OnStockLow(
  billing_counter2.LowStockHandler);
prod2.StockLow += 
  new ProductStock.OnStockLow(
  billing_counter2.LowStockHandler);

4) We setup Everything and we sell the products to see the notification when the stock goes below 5. We can also put a breakpoint on the below piece of code and examine how the Events work. Below is the code:

//Client 004: Now Let us Start serving 
//the customers on the Queue on 
//each counter
billing_counter1.Sales(prod1, 1);
billing_counter2.Sales(prod1, 2);
billing_counter2.Sales(prod3, 70);
billing_counter2.Sales(prod2, 1);
billing_counter1.Sales(prod2, 3);
billing_counter1.Sales(prod3, 5);

The complete Code Example and its output is given below:

Custom Events Example - Code & Output

using System;

namespace EventsP1
{
  //001: The class maintains Current Stock of 
  //the product. It publishes an LowStock 
  //event. Sends Notifications to the 
  //subscriber of the event when the product 
  //stock goes lower than 5
  public class ProductStock
  {
	  //001_1: Member Variable.
	  public string ProductName;
	  private int StockInHand;

    //001_2: Multicast delegate type that 
    //get coupled with the event.
    public delegate void OnStockLow(
      object sender, EventArgs e);

    //001_3: Published event (StockLow), 
    //that takes responsibility of sending 
    //notification to the scbscriber through 
    //the above Specified multicast delegate
    public event OnStockLow StockLow;

    //001_4: Constructor that Initializes 
    //the Stock
    public ProductStock(string Name, 
      int OpeningStock)
    {
	    ProductName = Name;
	    StockInHand = OpeningStock;
    }

    //001_5: This function reduces the stock 
    //based on the sales on the billing 
    //counters. When the stock in hand is 
    //lower than 5, it raises the 
    //StockLow event.
    public void ReduceStock(int SalesDone)
    {
	    StockInHand = StockInHand - SalesDone;
	    if (StockInHand < 5 )
	    {
		    EventArgs arg = new EventArgs();
		    StockLow(this, arg);
	    }
    }
	}

  //002: This class is for Sales Counter 
  //that performs the Sales on different 
  //counters and makes the billing. 
  //This class Subscribes to the Published 
  //event and Receives notification through 
  //Multicast delegate.
  public class Counter
  {
	  //002_1: Class member
	  private string CounterName;

	  //002_2: Constructor for Counter
	  public Counter(string Name)
	  {
		  CounterName = Name;
	  }

	  //002_2: Function that records the sales 
    //performed on the billing desk
	  public void Sales(ProductStock prod, 
      int howmuch)
	  {
		  Console.WriteLine(
        "{0} Sold {1} numbers", 
        prod.ProductName, 
        howmuch);
		  prod.ReduceStock(howmuch);
	  }

    //002_3: Function that acts as event 
    //handler for LowStock to receive the 
    //notification
    public void LowStockHandler(
      object Sender, EventArgs e)
    {
	    Console.WriteLine("Anouncement " +
        "on {0}: Stock of Product {1}" +
        " gone Low",
		    CounterName , 
        ((ProductStock) Sender).ProductName );
    }
	}

  class ProgramEntry
  {
	  [STAThread]
	  static void Main(string[] args)
	  {
		  //Client 001: Create Billing Counters
		  Counter billing_counter1 =
        new Counter("Jupiter");
		  Counter billing_counter2 =
        new Counter("Saturn");

      //Client 002: Create the Product Stocks
      ProductStock prod1 = new ProductStock(
        "Godrej Fridge", 7 );
      ProductStock prod2 = new ProductStock(
        "Sony CD Player", 6);
      ProductStock prod3 = new ProductStock(
        "Sony DVD", 800);

      //Client 003: Couple the Event with 
      //the Handler through the Delegate.
      prod1.StockLow += 
        new ProductStock.OnStockLow(
        billing_counter1.LowStockHandler);
      prod2.StockLow += 
        new ProductStock.OnStockLow(
        billing_counter1.LowStockHandler);
      prod1.StockLow += 
        new ProductStock.OnStockLow(
        billing_counter2.LowStockHandler);
      prod2.StockLow += 
        new ProductStock.OnStockLow(
        billing_counter2.LowStockHandler);		
	
      //Client 004: Now Let us Start serving 
      //the customers on the Queue on 
      //each counter
      billing_counter1.Sales(prod1, 1);
      billing_counter2.Sales(prod1, 2);
      billing_counter2.Sales(prod3, 70);
      billing_counter2.Sales(prod2, 1);
      billing_counter1.Sales(prod2, 3);
      billing_counter1.Sales(prod3, 5);
		}
	}
}
C# Code Output - Custom Events

C# Code Output - Custom Events

© 2018 sirama

Related Articles