Delegate Example with Anonymous method

Chvrsri
Posted by Chvrsri under Design Pattern & Practices category on | Points: 40 | Views : 4351
In my previous post i shown how to create a simple delegate now i will show how to implement delegate example using a Anonymous method .

Delegates Using Anonymous Methods :


Generally in normal Delegate Example the method is passed as a parameter but using Anonymous mehod , the complete method declaration and definition is declared in the Delegate itself . This is can be shown using a small example :

In my Example i take 2 strings as input and check whether they are same or not .

// My CodeBehind file is as follows : DelegatesAnonymous.aspx.cs



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

namespace DelegatesAnonymous
{
public partial class DelegatesAnonymous : System.Web.UI.Page
{
//Delegate is Created here
public delegate void Mydelegate(string name1, string name2);
protected void Page_Load(object sender, EventArgs e)
{

}

protected void EqualCheck_Click(object sender, EventArgs e)
{
//Anonymous Method for Delegate is Implemented here
Mydelegate del = delegate(string name1, string name2)
{
if (name1.Equals(name2))
{
lblDisplay.Text = "Both Strings are Equal";
}
else
{
lblDisplay.Text = "Both Strings are Not Equal";
}
};
del(firstString.Text, secondString.Text);
}
}
}


// Now comes the design page : DelegatesAnonymous.aspx


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="DelegateAnonymous.aspx.cs" Inherits="DelegatesAnonymous.DelegatesAnonymous" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2 align="center">CHECK FOR EQUALITY </h2>
<table align="center">
<tr>
<td>
<b>Enter First String ::</b>
</td>
<td>
<asp:TextBox ID="firstString" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<b> Enter Second String ::</b>
</td>
<td>
<asp:TextBox ID="secondString" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="EqualCheck" runat="server" Text="CHECK FOR EQUALITY"
onclick="EqualCheck_Click" />
</td>
</tr>
<tr><td></td></tr>
<tr>
<td colspan="2" align="center">
<asp:Label ID="lblDisplay" runat="server" ForeColor="Red" Font-Size="Large"></asp:Label>
</td>
</tr>
</table>

</asp:Content>


By this way we could achive the comparison of 2 strings using a Delegate with Anonymous Method .

Note : This code is for Explainatory purpose only there would be no high use for the purpose . Hope all understands.

Cheers !! Happy Coding !!!

Comments or Responses

Login to post response