What is delegates and how do we use them in asp.net?
There are different types in C#: int, bool, float etc. Also, you can declare custom types using keyword class or struct. The types above represent nouns or objects. Delegates are custom types that represent verbs or methods. Delegate is a C# keyword similar to class or struct.
The delegate is used to declare a reference type that can be used to encapsulate a named or 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 an 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" />