Tuesday, June 12, 2012

Event handling using Delegates in C#


In this post Event handling using Delegates in C#, we shall see the importance of Delegates in handling events in C#.

Delegates and Event handling go hand-in-hand, event handling requires the support of delegates to perform the Firing and handling of events, let us understand the importance of Delegates in event handling using a simple Math example.

In this example we will create a Windows form which will perform basic calculations like Addition, Subtraction, Multiplication and Division. The windows form will only get the data from the users and pass it to a class clsMath, the calculations will happen in the class clsMath and the class will make sure that the results are displayed in the Windows Form.

This might look simple, but there’s a point to note here, the Windows form will call the method in the class clsMath that’s all, it will not handle the results of the calculation, the class clsMath will make sure that the results are displayed in the main form using the event DisplayResult.
What we are trying to achieve is something like a callback to the main form, the main form calls the methods and just leaves it there, the class clsMath makes a callback to the main form by means of the event handler objMath_DisplayResult of the DisplayResult event.

First let us create the class clsMath.cs

// Declare the delegate to be used by the Event
public delegate void delegateCalculate(double dResult);
//
class clsMath
{
    // Declare the event to Display the Results
    public event delegateCalculate DisplayResult;

    // Add methods to do the calculation.
    // These methods will do the calculation and Fire the DisplayResult event
    // The DisplayResult event will be handled in the main form frmMath.   

    public void Add(int Number1, int Number2)
    {
        // Fire the DisplayResult event
        // This Event will be handled in the Main Form
        DisplayResult(Number1 + Number2);
    }
    //
    public void Subract(int Number1, int Number2)
    {
        // Fire the DisplayResult event
        // This Event will be handled in the Main Form
        DisplayResult(Number1 - Number2);
    }
    //
    public void Multiply(int Number1, int Number2)
    {
        // Fire the DisplayResult event
        // This Event will be handled in the Main Form
        DisplayResult(Number1 * Number2);
    }
    //
    public void Divide(int Number1, int Number2)
    {
        // Fire the DisplayResult event
        // This Event will be handled in the Main Form
        DisplayResult(Number1 / Number2);
    }
}

Now back in the main form, we shall add code to call the methods in the clsMath class, and declare an event handler for the DisplayResult event in the clsMath class.

public partial class frmMath : Form
{
    clsMath objMath;
    public frmMath()
    {
        InitializeComponent();
    }
    //
    private void frmMath_Load(object sender, EventArgs e)
    {
        // Create an Instance of the Math Class
        objMath = new clsMath();
        // Set the EventHandlers for the DisplayResults event
        objMath.DisplayResult += new delegateCalculate(objMath_DisplayResult);
    }
    //
    // Declare the Method which will Handle the Event DisplayResult
    void objMath_DisplayResult(double dResult)
    {
        txtResult.Text = dResult.ToString();
    }
    //
    // Call the Add Method in the clsMath Class
    private void btnAdd_Click(object sender, EventArgs e)
    {
        int nNumber1 = Convert.ToInt32(txtNumber1.Text);
        int nNumber2 = Convert.ToInt32(txtNumber2.Text);
        //
        objMath.Add(nNumber1, nNumber2);
    }
    //
    private void btnSub_Click(object sender, EventArgs e)
    {
        int nNumber1 = Convert.ToInt32(txtNumber1.Text);
        int nNumber2 = Convert.ToInt32(txtNumber2.Text);
        //
        objMath.Subract(nNumber1, nNumber2);
    }
    //
    private void btnMult_Click(object sender, EventArgs e)
    {
        int nNumber1 = Convert.ToInt32(txtNumber1.Text);
        int nNumber2 = Convert.ToInt32(txtNumber2.Text);
        //
        objMath.Multiply(nNumber1, nNumber2);
    }
    //
    private void btnDiv_Click(object sender, EventArgs e)
    {
        int nNumber1 = Convert.ToInt32(txtNumber1.Text);
        int nNumber2 = Convert.ToInt32(txtNumber2.Text);
        //
        objMath.Divide(nNumber1, nNumber2);
    }
}

That’s it we have created an Event, associated it with a Delegate, and handled the event.
It will be a bit confusions, the concept of Delegate itself is like that, go through the examples several times to get an idea of what is happening under the hood, it is this logic which is used under the hood for event handling in .Net.

At first look it might look that we are complicating a simple Math logic, but if you look into the logic carefully, you will understand that we are trying to achieve the basics of asynchronous programming, the main form frmMath calls the method of the class clsMath and forgets it (This is an Asynchronous call), the clsMath class performs the calculation and then raises the event handler in the main form (This is the Callback after completing the asynchronous operation).

Though this example does not perform Asynchronous programming, it starts with the concept, we shall see actual asynchronous programming in the upcoming posts.



Related Posts
Delegates in C#
Multicast Delegates
Event handling using Delegates in C#
Synchronous call using Delegates in C#
Asynchronous callback using Delegates in C#

Search Flipkart Products:
Flipkart.com

No comments: