Click here to Skip to main content
15,879,239 members
Articles / Programming Languages / C#
Tip/Trick

Simple and Best Example of How to Work with Event Handlers

Rate me:
Please Sign up or sign in to vote.
1.00/5 (2 votes)
29 Jun 2012CPOL 24.5K   4   4
Simple and best example of how to work with Event Handlers.

Introduction

This article tries to explain the concept of Event Handling in C#.  This article uses a small scenario wherein a Wholesaler(Publisher) keeps changing the price of his article. There are Retailers(Subscriber)who want to register themselves for this price so that they can do the business... This is just like a stock broking or a bullion market...

Whenever the Publisher changes the Price it automatically changes the price at the Subscriber....

Initially create a class named Wholesaler which creates an event and an event and an EventHandler.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharpPractice_Latest
{
    public class Wholesaler
    {
        private static int _price;
        
        //Declaring a delegate that handles the event.....
        public delegate void PriceChangeHandler(Wholesaler sender, PriceChangeEventArgs PCE);
        
        //Declaring an event....
        public event PriceChangeHandler PriceChange;
        
        public int Price
        {
            get
            {
                return Wholesaler._price;
            }
            set
            {
                Wholesaler._price = value;
                //Firing the event whenever the price is changed.
                OnPriceChange(this, new PriceChangeEventArgs(value));
            }
        }
        //This is the key method that propagates the event
        public void OnPriceChange(Wholesaler sender, PriceChangeEventArgs PCE)
        {
            PriceChange(this, PCE);
        }
    }
}

Creating a class that extends the EventArgs class of the .NET Framework, to carry the event data.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpPractice_Latest
{
    public class PriceChangeEventArgs : EventArgs
    {
        public int NewPrice { get; set; }

        public PriceChangeEventArgs(int NewPrice)
        {
            this.NewPrice = NewPrice;
        }
    }

Create a class Retailer (Subscriber) that is interested in the event fired by the wholesaler (Publisher). You can create any number of subscribers such as Retailer1, Retailer2, and so on to subsribe to the event fired by the Publisher.....

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpPractice_Latest
{
    public class Retailer1
    {
        private int _price;

        public int Price
        {
            get { return _price; }
            set { _price = value; }
        }

        public void subscribe(Wholesaler P)
        {
            P.PriceChange += new Wholesaler.PriceChangeHandler(UpdatePrice);
        }

        public void unsubscribe(Wholesaler P)
        {
            P.PriceChange -= new Wholesaler.PriceChangeHandler(UpdatePrice);
        }

        private void UpdatePrice(Wholesaler P, PriceChangeEventArgs PCE)
        {
            this.Price = PCE.NewPrice;
        }
    }
}

Finally, the execution path.... How this works!!!!!!!!!!!!!

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpPractice_Latest
{
    class Program
    {

        static void Main(string[] args)
        {

            Wholesaler P = new Wholesaler();
            Retailer1 R1 = new Retailer1();
            Retailer2 R2 = new Retailer2();
            R1.subscribe(P);
            R2.subscribe(P);

            Console.Out.WriteLine("Initially the price with Wholesaler is Rs.{0}", P.Price);
            Console.Out.WriteLine("Initially the price with Retailer1 is Rs.{0}", R1.Price);
            Console.Out.WriteLine("Initially the price with Retailer2 is Rs.{0}", R2.Price);

            Console.Out.WriteLine("Now, changing the price with Wholesaler to Rs.100");

            P.Price = 100;

            Console.Out.WriteLine("Now the price with Wholesaler is Rs.{0}", P.Price);
            Console.Out.WriteLine("Now the price with Retailer1 is Rs.{0}", R1.Price);
            Console.Out.WriteLine("Now the price with Retailer2 is Rs.{0}", R2.Price);

            Console.Out.WriteLine("Retailer1 opted to withdraw the link with Wholesaler");
            R1.unsubscribe(P);
            Console.Out.WriteLine("Now, changing the price with Wholesaler to Rs.200");

            P.Price = 200;

            Console.Out.WriteLine("Now the price with Wholesaler is Rs.{0}", P.Price);
            Console.Out.WriteLine("Now the price with Retailer1 is Rs.{0}", R1.Price);
            Console.Out.WriteLine("Now the price with Retailer2 is Rs.{0}", R2.Price);


            Console.ReadLine();
        }
    }
}

The output is: 

Initially the price with Wholesaler is Rs.0
Initially the price with Retailer1 is Rs.0
Initially the price with Retailer2 is Rs.0
Now, changing the price with Wholesaler to Rs.100
Now the price with Wholesaler is Rs.100
Now the price with Retailer1 is Rs.100
Now the price with Retailer2 is Rs.100
Retailer1 opted to withdraw the link with Wholesaler
Now, changing the price with Wholesaler to Rs.200
Now the price with Wholesaler is Rs.200
Now the price with Retailer1 is Rs.100
Now the price with Retailer2 is Rs.200

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Paulo Zemek5-Jul-12 5:19
mvaPaulo Zemek5-Jul-12 5:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.