pavanarya

Let us share the knowledge

Delegates in c#

with 4 comments

Delegates in .Net are something like function pointers in c or c++.
Delegates are .Net objects that points to some functions and the criteria is the delegates signature as well as functions signature should match.

So when ever we are creating and making use of Delegates we are supposed to keep certain points in our mind.

1.The delegate’s and the functions signature should be same.
2. Number of parameters in the delegate should match with functions parameter list.

Delegates are derived from Delegates class and they are sealed and we cannot extend delegates.

Steps For Creating and Using Delegates:

Creation of Delegates involves 4 steps. They are

1.Declare a delegate as follows

public delegate int MyDelegate(int num1, int num2);

2. Creating a Method that exactly matches the definition of the delegate.

 private int add(int a, int b)
        {
            return a + b;
        }

3.Pointing the method to the delegate.

MyDelegate del=add;

//or

MyDelegate del=new MyDelegate(add);

4.Invoking the delegate

del(1,2)

Example Of Delegate:

My Requirement:

I am having few methods in a class like add,sub,multiply that takes two values as inputs. Something like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyDelegates
{
    public class DelegateClass
    {
        public int add(int a, int b)
        {
            return a + b;
        }

        public int sub(int a, int b)
        {
            return a - b;
        }
    }
}

Now i am having an aspx.cs page and i want to make use of the methods declared in the above scenario by creating an object to the class that contains the methods and then invoking the methods.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyDelegates
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MyDelegates.DelegateClass cls = new DelegateClass();
          string operation = txtbox1.Text;
         if(operation=="add")
          {
          int val1= cls.Add(1,2);
           }
           else if(operation=="sub")
          int val2=cls.sub(20,10);

        }
    }
}

For suppose if there is new function Multiply added to the class Delegates Class and we want to make use of that in our aspx.cs file.

So to accomplish that we are supposed to change the logic of aspx.cs file and also we are supposed to add the method to the class(DelegateClass) as follow

    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MyDelegates.DelegateClass cls = new DelegateClass();
          string operation = txtbox1.Text;
          if(operation=="add")
            {
              int val1= cls.Add(1,2);
             }
           else if(operation=="sub")
             {
              int val2=cls.sub(20,10);
             }
          else if(operation=="multiply")
           {
               int val3=cls.Multiply(2,5);
            }

        }
    }
}

To prevent the changes in the aspx.cs file when ever we add a new function in the DelegateClass i am planning to call a intermediate variable which in turn points to the actual method.

Now in this case Delegates comes into picture.

So what i am doing here is i am creating a delegate that points to either add or sub or multiply.

So based on the operationtype i am assigning the delegate with add or sub or multiply in the method performOperation().

Now the performOperationMethod() returns the delegate that points to either add or sub or multiply.
DelegateClass.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyDelegates
{
    public class DelegateClass
    {
        public delegate int MyDelegate(int num1, int num2); //declaring a delegate

        private int add(int a, int b) //creating methods that match delegate type
        {
            return a + b;
        }

        private int sub(int a, int b)
        {
            return a - b;
        }

        private int Multiply(int a, int b)
        {
            return a * b;
        }

        public MyDelegate performOperation(string operationtype)
        {
            MyDelegate d=null;
            if (operationtype=="add")
            {
                d = add;                                //Assigning the delegates
            }
            if (operationtype == "sub")
            {
                d = sub;
            }
            if (operationtype == "multiply")
            {
                d = Multiply;
            }
            return d;
        }
    }
}

So now in the aspx.cs file i can avoid the logic of if else conditions to call the add,multiply,sub methods and that is taken care in the DelegateClass.

Now instead of calling the method like add or sub or Multiply i am calling the delegate returned by the performOperationMethod() which is going to take the appropriate decision of assigning the method to delegate.

So the advantage of this is with no change in the UI logic we are able to call different method in the DelegateClass

webForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyDelegates
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MyDelegates.DelegateClass cls = new DelegateClass(); //Creating an object for the Class 

            MyDelegates.DelegateClass.MyDelegate delgat= cls.performOperation(txtbox1.Text);
          int value=  delgat(1, 10);

        }
    }
}
About these ads

Written by pavanarya

March 25, 2012 at 5:09 pm

Posted in Asp.net, c#

4 Responses

Subscribe to comments with RSS.

  1. [...] my previous post we saw about the creation of Delegates and using [...]

  2. Hi Pav1!
    Good article.
    In the eample txtbox1 will have the operation text(“add” or “Sub” or “multiply”) right!

    RK

    March 26, 2012 at 11:29 am

  3. [...] my previous post we saw about the creation of Delegates and using [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 67 other followers

%d bloggers like this: