Friday, March 25, 2011

Delegates in asp.net c#


Introduction

Delegate is like a buzz word in C#.NET programming. In this article, I explain delegates, multicast delegatesand their usage with the help of simple C# programs.

What is a Delegate?

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

Advantages

  • Encapsulating the method's call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration


public delegate type_of_delegate delegate_name()
Example:

public delegate int mydelegate(int delvar1,int delvar2)

Note

  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)

Sample Program using Delegate


public delegate double Delegate_Prod(int a,int b);
class Class1
{
    static double fn_Prodvalues(int val1,int val2)
    {
        return val1*val2;
    }
    static void Main(string[] args)
    {
        //Creating the Delegate Instance
        Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
        Console.Write("Please Enter Values");
        int v1 = Int32.Parse(Console.ReadLine());
        int v2 = Int32.Parse(Console.ReadLine());
        //use a delegate for processing
        double res = delObj(v1,v2);
        Console.WriteLine ("Result :"+res);
        Console.ReadLine();
    }
}

Explanation

Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod" is declared with double return type and accepts only two integer parameters.
Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)
Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:

Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:

delObj(v1,v2);
Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.

Multicast Delegate

What is Multicast Delegate?

It is a delegate which holds the reference of more than one method.
Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate


delegate void Delegate_Multicast(int x, int y);
Class Class2
{
    static void Method1(int x, int y)
    {
        Console.WriteLine("You r in Method 1");
    }

    static void Method2(int x, int y)
    {
        Console.WriteLine("You r in Method 2");
    }

    public static void "on" />Main()
    {
        Delegate_Multicast func = new Delegate_Multicast(Method1);
        func += new Delegate_Multicast(Method2);
        func(1,2);             // Method1 and Method2 are called
        func -= new Delegate_Multicast(Method1);
        func(2,3);             // Only Method2 is called
    }
}

Explanation

In the above example, you can see that two methods are defined named method1 and method2 which take two integer parameters and return type as void.
In the main method, the Delegate object is created using the following statement:

Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed using the -= operator.

ASP.NET Advanced Technologies Tutorial

This tutorial demonstrates how to sort employee of one company by the employee's salary asc with the Delegate technique and bubble sort. 

This tutorial demonstrates how to sort employee of one company by the employee's salary asc with the Delegate technique and bubble sort. And this tutorial only using the default namespace. 
A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value.

First, we need to  Declares a delegate. And we use the btnSorter_Click event to do the work.
public delegate bool CompareOB(object lhs,object rhs);

protected void btnSorter_Click(object sender, EventArgs e)
{
string employeelist = "";
Employee[] employees =
{
new Employee(this.lbljoy.Text.Trim(),Convert.ToDecimal(this.lblsalaryjoy.Text.Trim())),
new Employee(this.lbljake.Text.Trim(),Convert.ToDecimal(this.lblsalaryjake.Text.Trim())),
new Employee(this.lblpetter.Text.Trim(),Convert.ToDecimal(this.lblsalarypetter.Text.Trim())),
new Employee(this.lblsam.Text.Trim(),Convert.ToDecimal(this.lblsalarysam.Text.Trim()))
};
CompareOB employeeCompareOB = new CompareOB(Employee.isGreater);
BubbleSorter.Sort(employees, employeeCompareOB);
for(int i=0;i<employees.Length;i++)
employeelist += employees[i].ToString() + "<br>";

this.lblResult.Text = employeelist.ToString();

}
We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.
The code of the Employee class as follows

public class Employee
{
private string name;
private decimal salary;

public Employee(string name,decimal salary)
{
this.name = name;
this.salary = salary;
}
public override string ToString()
{
return string.Format(name +":{0:C}",salary);
}
public static bool isGreater(object lhs, object rhs)
{
Employee employeelhs = (Employee)lhs;
Employee employeerhs = (Employee)rhs;
return (employeerhs.salary > employeelhs.salary) ? true : false;
}
}
Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!
The code of the BubbleSorter class as follows

public class BubbleSorter
{
public static void Sort(object[] sortArry, CompareOB gtMethod)
{
for (int i = 0; i < sortArry.Length; i++)
{
for (int j = i + 1; j < sortArry.Length; j++)
{
if(gtMethod(sortArry[j],sortArry[i]))
{
object temp = sortArry[i];
sortArry[i] = sortArry[j];
sortArry[j] = temp;
}
}
}
}
}
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.
The front end BubbleSorterWithDelegateVB.aspx page looks something like this: 

<table>
<tr>
<td style="width: 100px">name</td>
<td style="width: 100px">salary</td>
</tr>
<tr>
<td style="width: 100px">
<asp:Label ID="lbljoy" runat="server" Text="joy"></asp:Label></td>
<td style="width: 100px">
<asp:Label ID="lblsalaryjoy" runat="server" Text="20000"></asp:Label></td>
</tr>
<tr>
<td style="width: 100px">
<asp:Label ID="lbljake" runat="server" Text="jake"></asp:Label></td>
<td style="width: 100px">
<asp:Label ID="lblsalaryjake" runat="server" Text="10000"></asp:Label></td>
</tr>
<tr>
<td style="width: 100px; height: 21px;">
<asp:Label ID="lblpetter" runat="server" Text="petter"></asp:Label></td>
<td style="width: 100px; height: 21px;">
<asp:Label ID="lblsalarypetter" runat="server" Text="25000"></asp:Label></td>
</tr>
<tr>
<td style="width: 100px">
<asp:Label ID="lblsam" runat="server" Text="sam"></asp:Label></td>
<td style="width: 100px">
<asp:Label ID="lblsalarysam" runat="server" Text="23000"></asp:Label></td>
</tr>
</table>
&nbsp;
<asp:Button ID="btnSorter" runat="server" Text="Sort" Width="78px" OnClick="btnSorter_Click" /><br />
<br />
<asp:Label ID="Label1" runat="server" Text="Display the sorted result:"></asp:Label>&nbsp;&nbsp;<br />
<asp:Label ID="lblResult" runat="server" ForeColor="Red"></asp:Label>
If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.
The flow for the code behind page is as follows.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace BubbleSorter
{
public delegate bool CompareOB(object lhs,object rhs);

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSorter_Click(object sender, EventArgs e)
{
string employeelist = "";
Employee[] employees =
{
new Employee(this.lbljoy.Text.Trim(),Convert.ToDecimal(this.lblsalaryjoy.Text.Trim())),
new Employee(this.lbljake.Text.Trim(),Convert.ToDecimal(this.lblsalaryjake.Text.Trim())),
new Employee(this.lblpetter.Text.Trim(),Convert.ToDecimal(this.lblsalarypetter.Text.Trim())),
new Employee(this.lblsam.Text.Trim(),Convert.ToDecimal(this.lblsalarysam.Text.Trim()))
};
CompareOB employeeCompareOB = new CompareOB(Employee.isGreater);
BubbleSorter.Sort(employees, employeeCompareOB);
for(int i=0;i<employees.Length;i++)
employeelist += employees[i].ToString() + "<br>";

this.lblResult.Text = employeelist.ToString();
}
}

public class Employee
{
private string name;
private decimal salary;

public Employee(string name,decimal salary)
{
this.name = name;
this.salary = salary;
}
public override string ToString()
{
return string.Format(name +":{0:C}",salary);
}
public static bool isGreater(object lhs, object rhs)
{
Employee employeelhs = (Employee)lhs;
Employee employeerhs = (Employee)rhs;
return (employeerhs.salary > employeelhs.salary) ? true : false;
}
}

public class BubbleSorter
{
public static void Sort(object[] sortArry, CompareOB gtMethod)
{
for (int i = 0; i < sortArry.Length; i++)
{
for (int j = i + 1; j < sortArry.Length; j++)
{
if(gtMethod(sortArry[j],sortArry[i]))
{
object temp = sortArry[i];
sortArry[i] = sortArry[j];
sortArry[j] = temp;
}
}
}
}
}
}

1 comment :

  1. Hi Anil,

    I have doubt regarding Using of Delegate in Web-Based Applications.

    Is it recommended that always avoid to use Delegate in programming of Website applications of .Net ??

    Looking forward for your reply !


    Thanks
    Shubhank

    ReplyDelete