Friday, August 5, 2011

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" />

No comments:

Post a Comment