Click here to Skip to main content
Click here to Skip to main content

Simple and Best Example of How to Work with Event Handlers

By , 29 Jun 2012
 

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.

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.

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

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

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)

About the Author

No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Question[My vote of 1] error prone..memberSeishin#29-Jun-12 9:06 
AnswerRe: [My vote of 1] error prone..memberKimayoi29-Jun-12 12:20 

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 29 Jun 2012
Article Copyright 2012 by Bhavanarayana.Vempati
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid