What is delegates and how do we use them in asp.net?

The delegate is used to declare a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure. In asp.net we are using delegates to create custom events for custom controls.

For example, custom pager control most likely needs to have PageChanged event.

We can declare it like this:

public delegate void PageChangedHandler(object sender, EventArgs e);

public event PageChangedHandler PageChanged;

 

Then whenever we need to fire event:

 

if (PageChanged != null) // Checks if user assigned any event handler

    PageChanged(this, new EventArgs());

 

And then we can use our custom pager control as follow:

 

<cc:PostsPager ID="PostsPager" runat="server" OnPageChanged="PostsPager_PageChanged" />

 

 


Wednesday, July 09, 2008 | Comments (4) | Add Comment

Comments

Gravatar

Re:What is delegates and how do we use them in asp.net?

Nice

10/7/2008 4:45:27 AM | by jitender
Gravatar

Re:What is delegates and how do we use them in asp.net?

It is good, example , but there should be more explaination.

9/1/2009 11:41:36 PM | by piyush
Gravatar

Re:What is delegates and how do we use them in asp.net?

please explain the delegates with a suitable examle which i can understand

4/16/2010 12:17:23 AM | by rakesh
Gravatar

There are simple types such as int, bool, string. Delegate is a type for a function method. By declaring delegate you are declaring signature of method stub. In ASP.NET it mostly useful for events, example of such usage I have below.

Gravatar

Re:What is delegates and how do we use them in asp.net?

it should be preety clear

5/11/2010 3:09:39 AM | by swati

New Comment

Your Name:
Email (for internal use only):
Subject:
Comment:
 
Code above:

Categories

Recent Tweets

Valid XHTML 1.0 Transitional