C# Custom Events Explained With Example

Updated on December 5, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like playing video games & 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 | Source

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 | Source

© 2018 sirama

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)