Search

Apr 29, 2008

Anonymous Delegate!!!

Here is one more powerful use of Delegate.

Till now I familiar with simple delegate and multicast delegate. Now one more and I found very good type of Delegate that is Anonymous Delegate.

In general Anonymous delegates are just a convenient way to declare a method without naming it.
Or
Passing a method to a method by typing in the method (including the curly braces), rather than the name of a method declared somewhere else.

A delegate is something like a function pointer, you can pass it to another method (as a parameter) and execute it remotely. Usually they are just a pointer to a method defined somewhere else in the class, but in the case of anonymous ones, they are defined in place. This makes it easier, because like this you don't need to look for a name


protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnLogin.Click += delegate { objClass.ValidateUser(); };
}
This is simple delegate with out any parameter. The click event of Login button will be handled by function ValidateUser of some class.

Now if you want any parameter in your delegate then before open curly braces you can add it just like simple function.

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.btnLogin.Click += delegate(object sender, EventArgs args) { presenter.ValidateUser(); };
}
As its function without name, you can also write your code there.

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
rptUserList.ItemCommand += delegate(object source, RepeaterCommandEventArgs ee)
{
Console.Write(int.Parse(ee.CommandArgument.ToString()));
objClass.GetDetailsById(int.Parse(ee.CommandArgument.ToString()));
//display the details
Console.Write(objClass.Name);

};
}
That is the basic idea.

Apr 28, 2008

Delegates and Events in C# / .NET

I come accross a good link for how Delegates and Events works in C#.

What are delegats, what is multicast-delegate handling events with delegates... all this with simple and understandable example.

Read more Delegates and Events in C# / .NET