0

I am trying to study the delegate concept in c#.

I did a sample of delegate as I studied. But I did not understood the correct situation where we using its concept effectively. Can any one please suggest a easy understandable situation where we use delegate.

I know the working of delegates. But still not cleared where it effectively use.

I posted my code below. Please let me know if any mistakes I did in the sample.

Thankx in advance.

ChangePassword.ascx

  <%@ Control Language="C#" AutoEventWireup="true" CodeFile="ChangePassword.ascx.cs" Inherits="User_Controls_ChangePassword" %>

<div style="width:500px;clear:both;">
<div style="width:100%; clear:both;">
    <div style="width:150px; float:left;">
        <asp:Label ID="newPassword" runat="server" Text="New Password"></asp:Label>
    </div>
    <div style="width:100px; float:left;">
        <asp:TextBox ID="newPassText" runat="server" Width="200"></asp:TextBox>
    </div>
</div>
<div style="width:100%; clear:both;padding-top:20px;">
    <div style="width:150px; float:left;">
        <asp:Label ID="Label1" runat="server" Text="Confirm New Password"></asp:Label>
    </div>
    <div style="width:100px; float:left;">
        <asp:TextBox ID="confirmNewPass" runat="server" Width="200"></asp:TextBox>
    </div>
</div>
<div style="width:100%; clear:both;padding-top:20px;">
    <div style="width:150px; float:left;">
        <asp:Label ID="Label2" runat="server" Text="&nbsp;"></asp:Label>
    </div>
    <div style="width:207px; float:left;">
        <div style="float:left;">
            <asp:Button ID="changePass" runat="server" Text="Change"  /> 
        </div>
        <div style="float:right;">
            <asp:Button ID="cancelButton" runat="server" Text="Cancel" /> 
        </div>
    </div>
</div>
<div style="width:100%; clear:both;padding-top:20px;">
    <div style="width:350px; float:left;">
        <asp:Label ID="successMessage" runat="server" Text="Passwords Changed.." ForeColor="Red" Font-Bold="true" Visible="false"></asp:Label>
    </div>
</div>

ChangePassword.ascx.cs

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

public partial class User_Controls_ChangePassword : System.Web.UI.UserControl
{
    public delegate void ChangePasswordDelegate(object sender, ChangePasswordEventArgs e);
    public event ChangePasswordDelegate ChangePasswordEvent;

    protected void Page_Load(object sender, EventArgs e)
    {
        changePass.Click += new EventHandler(changePass_Click);
    }

    void changePass_Click(object sender, EventArgs e)
    {
        ChangePasswordEvent(sender, new ChangePasswordEventArgs(newPassText.Text, this) );
    }
}


public class ChangePasswordEventArgs : EventArgs
{
    private string _newPassword = "";
    private object _parent = null;

public string NewPassword
{
    get
    {
        return _newPassword;
    }
    set
    {
        _newPassword = value;
    }
}

public object Parent
{
    get
    {
        return _parent;
    }
    set
    {
        _parent = value;
    }
}

public ChangePasswordEventArgs()
{    }

public ChangePasswordEventArgs(string pass , object parent)
{
    _newPassword = pass;
    _parent = parent;
}

}

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register TagName="ChangePasword" TagPrefix="MY" Src="~/User Controls/ChangePassword.ascx" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
     <MY:ChangePasword ID="passControl" runat="server" />
</asp:Content>

Default.aspx.cs

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
{
    passControl.ChangePasswordEvent += new User_Controls_ChangePassword.ChangePasswordDelegate(passControl_ChangePasswordEvent);
}

void passControl_ChangePasswordEvent(object sender, ChangePasswordEventArgs e)
{
    if (e.Parent != null)
    {
        User_Controls_ChangePassword cp = (User_Controls_ChangePassword)e.Parent;
        cp.FindControl("successMessage").Visible = true;
    }
}

}

Cœur
  • 37,241
  • 25
  • 195
  • 267
Arun
  • 3,478
  • 8
  • 33
  • 46

3 Answers3

0

Thank you Meysam. He commented on my question with a very useful link regarding delegates. Now I have a clear idea about delegates and also about EventArgs. Here is the link,

http://www.codeproject.com/Articles/4773/Events-and-Delegates-Simplified

Hope it will help others too.

Arun
  • 3,478
  • 8
  • 33
  • 46
0

You can see a good example of usage of delegates in lambda expressions. It is used frequently in LINQ.

Take a look here: Lambda Expressions and Expression Trees

Also you can refer to this post.

The example you have provided is form the category Event handlers (for GUI and more)

Hope it helps!

Community
  • 1
  • 1
0

Regarding the use of delegates for event handling there is a generic solution for it since .NET 2.0

EventHandler<TEventArgs>

Handling events using this doesn't require explicit use of new delegates.

This event declaration is enough:

event EventHandler<ChangePasswordEventArgs> ChangingPassword;

In your code when raising an event you should check for subscribers:

void changePass_Click(object sender, EventArgs e)
{

    if(ChangePasswordEvent != null)
        ChangePasswordEvent(sender, 
            new ChangePasswordEventArgs(newPassText.Text, this));
}   

If you don't check for subscribers and there are none, the event would throw an exception. In a multi threaded application you should use this approach instead.


Regarding the general use for delegates, the "raw" delegate is seldom used directly, but events, lambdas and expression trees use delegates as the underlying mechanism. The only direct use for delegates I have made is for event handling and async operations using the Begin/EndInvoke pattern.

See this article for an explanation of delegates, lambdas and anonymous methods.

Community
  • 1
  • 1
PHeiberg
  • 29,411
  • 6
  • 59
  • 81