Friday, March 26, 2010

Anonymous methods

btnSave.Click += new EventHandler (btnSave_Click);

Have you seen this piece of code? Yes definitely I guess everyone knows this and aware why we use it. So when I use the code like above I need to implement the method btnSave_Click

If you have started using .net 2.0 or above you can also do this using anonymous method which is very simpler to use as below


btnSave.Click += delegate(object sender, EventArgs e)
{
SaveChanges();
MessageBox.Show("Data has been saved successfully");
}


This piece is called Anonymous method which allows declaration of inline methods without specifying the method names. It uses delegates and it is very useful when we have short code.

No comments:

Post a Comment