Wednesday 1 April 2015

Delegates in C#

Delegates in C#

Delegates, by the name itself we can understand that there is some concept of hand-shaking or communication between objects.

Yes, you are right. 

Delegates are nothing but the same concept of Pointers to Functions, in C or C++. As we know that C# does not support pointers concept, so they have come with the solution using Delegates. 

Delegates, when I first heard this, I was totally blank. But when I started learning this and implementing in my code, it is easy.

Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

It has some properties like,
·         It is used to call a method asynchronously
·         It is similar to C++ function pointers, but are type safe.
·         It can be used to define callback methods.
·         It allows methods to pass as parameters.
·         It can be chained together, multiple methods can be
called on a single event.

Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.


Let us understand the Delegates, by writing a small Windows Form Application.

Step 1: Open Visual Studio and create a new Windows Form Application.


After the creation, in Form1.cs add the following controls, to look like this.


Ok. I think now we can start understanding the Delegates concept and see how it works.

Declaring Delegates

Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to a method, which has the same signature as that of the delegate.

Syntax for declaring the Delegates.

·         delegate <return type> <delegate-name> <parameter list>

Example:

                                     delegate int NumberCalculation(int num1, int num2);


So, in the above declaration NumberCalculation is a method which accepts two integers and returns an integer value.

Instantiating Delegates


After the Delegate declaration, it can be associated with a particular method by only creating the object of the Delegate with the new keyword.

Example:
NumberCalculation ncAdd = new NumberCalculation(AddNum);
       NumberCalculation ncMul = new NumberCalculation(MulNum);

Now let’s implement these things in the practical way so that we can understand it easily.

Open the Form1.cs file in the Design Mode, and double click the Call button, it will create an event handler function the Form1.cs file.


Now let’s write the code for this.
  • First let us declare the Delegate, we will declare that in Global level.
  • Declare a static int variable num.




·     
  • Let’s create methods AddNum, MulNum and getNum, which accepts two parameters and returns one integer value depending upon the calculation and getNum to return the calculated value to the main function.


  • Now we will instantiate the Delegate, as I explained above.
  •       See normally when we have to call a method we have to pass the parameters to it for executing the method, and if we don’t pass the compiler will throw error, but in the concept of Delegate we will just pass the method name as parameter, that’s it (without passing parameters to the method AddNum or MulNum).



  • Now we will start writing the code to accept these values from the UI and pass it to the Delegate and get our Calculation done.


  • The full code for this is.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Delegate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        static int num;
        delegate int NumberCalculation(int num1, int num2);
        private void btnCall_Click(object sender, EventArgs e)
        {
            try
            {
                NumberCalculation ncAdd = new NumberCalculation(AddNum);
                NumberCalculation ncMul = new NumberCalculation(MulNum);

                ncAdd(Convert.ToInt16(textBox1.Text), Convert.ToInt16(textBox2.Text));
                lblResult1Value.Text = "Addition - " + Convert.ToString(getNum());
                ncMul(Convert.ToInt16(textBox1.Text), Convert.ToInt16(textBox2.Text));
                lblResult2Value.Text = "Multiplication - " + Convert.ToString(getNum());

            }
            catch (Exception ex)
            {
            }
        }

        public static int AddNum(int p, int q)
        {
            num = p + q;
            return num;
        }

        public static int MulNum(int p, int q)
        {
            num = p * q;
            return num;
        }

        public static int getNum()
        {
            return num;
        }
    }
}

  • When you run this application and give the values in the textbox and press the button Call. The Delegate is processed and gives out the result as per the calculation.
  • Click on the Call button.

  • You can see that Addition and the Multiplication part is done correctly.
  • Let's understand the code
    •    So we declared and instantiated the Delegate.
    •  When we start the compiler to run the program, it will first create the object for the
      • NumberCalculation ncAdd = new NumberCalculation(AddNum);
    •    Then it will call the ncAdd method with the two parameters, which we give in the textbox and calculates and returns the value. 
  • So till now what we learned is a Simple Delegate.

    Multicasting Delegate


  • Multicasting Delegates can be composed by “+” operator.
      • NumberCalculation nc;
      •     nc = ncAdd + ncMul;
  • Now the composed delegate will call the two Delegates from which it is composed from.
  • You can compose only same type of Delegates.
  • Using “-“operator, the component Delegate can be removed from the composed Delegate.
  • When you the application, you will getting the output as like this.

  • You can see that the value is 29
    • We have done ncAdd + ncMul.
    • First it will add 5+4=9 and it will be stored in the static variable num.
    • Now it will multiply 5*4=20 and then it will add the value to num.
    •    So 20+9=29.
    •    Same is the vice versa, like ncAdd – ncMul will be 9. As it will only consider ncAdd and do the calculation for addition, and returns the result.
  •     If you change that to ncMul + ncAdd, then the result will be 12.
  • Code for the Multicasting Delegate is as follows.

static int num;
        delegate int NumberCalculation(int num1, int num2);
        private void btnCall_Click(object sender, EventArgs e)
        {
            try
            {

                //lblResult3Value.Visible = false;
                NumberCalculation ncAdd = new NumberCalculation(AddNum);
                NumberCalculation ncMul = new NumberCalculation(MulNum);

               

                //Multicasting Delegate

                lblResult1Value.Visible = lblResult2Value.Visible = false;
                NumberCalculation nc;
                nc = ncAdd - ncMul;
                nc(Convert.ToInt16(textBox1.Text), Convert.ToInt16(textBox2.Text));
                lblResult3Value.Text = "Multicast - " + Convert.ToString(getNum());

            }
            catch (Exception ex)
            {
            }
        }

        public static int AddNum(int p, int q)
        {
            num += p + q;
            return num;
        }

        public static int MulNum(int p, int q)
        {
            num += p * q;
            return num;
        }

        public static int getNum()
        {
            return num;
        }





Happy Coding !!!!!!!!!!!!!