Friday, January 22, 2010

Anonymous Method in C#

What is Anonymous Method?

          Anonymous Method is a normal method which one didn't have the calling name. ( in-line Code snippet).


What is the Use of Anonymous Methods?

            1. Which will helps to increase the readability and maintainability of the Code.
            2. To reduce the coding overhead in instantiating delegates because you do not have to create a separate method.
            3. The code stays closer together which makes it easier to follow and maintain.

Where we can use  Anonymous Methods?

             1.  When we have simple methods that won't be reused.

Examples :

1. Event Handler (without using anonymous methods)

btnSubmit.Click += new EventHandler (btnSubmit_Click);

  private void btnSubmit_Click(object sender, EventArgs e) 
  { 
       SaveEmployeeData(); 
       lblStatus.Text = "Successfully saved";
  }

2. Event Handler (using anonymous methods)

      btnSubmit.Click += delegate { SaveEmployeeData();  lblStatus.Text = "Successfully saved"; };

3. Event Handler ( using Anonymous Methods, with a parameter list )

     btnSubmit.Click += delegate(object sender, EventArgs e)
     {
          lblProcess.Text = "You clicked : " + ((Button)sender).Text;
          SaveEmployeeData();
           lblStatus.Text = "Successfully saved";
      }

Sample Code Snippet :

   delegate void DisplayMessage(string s);

   class SampleAnonymous
  {
     static void Main(string[] args)
    {
           DisplayMessage oDispMsg = delegate(String Msg)
          {
                  Console.WriteLine(Msg);
           };

     oDispMsg("Hi, this from the anonymous delegate call");

     // To Create an instance of delegate. 
     oDispMsg = new DisplayMessage(SampleAnonymous.toDisplay);

     oDispMsg("Hi, This is without delegate call, [ Old Style ]");
     Console.ReadLine();
 }

  static void toDisplay(string Msg)
  {
      Console.WriteLine(Msg);
  }
 }

Output :




Note : To get clear cut idea , put a break points and run this code snippet.


Thank You.

No comments: