C# Anonymous method

This article discusses the basics of anonymous methods in C# and how to take advantage of them by implementing them in your applications.

An anonymous method is a block of code that is used as the parameter for the Delegate.

Anonymous method allows coder to pass block of code rather than the name of the method. Creating a anonymous method is a way to pass a code block as delegate parameter.

Benefits:

  1. To reduce code the amount of code 
  2. To reduce complexity of code. 
  3. To increase readability of code. 
  4. Anonymous method can use any local variable declared outside of method.

Rules

  1. Cannot have jump statement that targets outside the anonymous method. 
  2. Jump statement from outside of anonymous method cannot target inside anonymous method. 
  3. Anonymous method cannot use Ref and Out parameter from outside of anonymous method.

Synatx:

Button1.Click+= delegate(Object o, EventArgs e)
{
      MessageBox.Show("SCOTT"); 
}

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication4

{

    class Program

    {

        // Decelaring Delegate

        public delegate void Display(String msg);

        static void Main(string[] args)

        {

            // Delegate using anonymous method

            Display del = delegate(string par)

            Display del = delegate(string par)

            {

                Console.WriteLine("{0}", par);

            };

            // Invoking delegate

            del("Christ");

            Console.ReadLine();

        }

    }

}

In above code, Christ will get display as output.  In above code, block of code is getting passes as argument of delegate rather than name of the method.

Scope of the variable

The scope of variable of an anonymous method is the anonymous method block.

Anonymous method does not help speeding up the execution process because for block of code, .Net generates the Anonymous name.

Up Next
    Ebook Download
    View all
    Learn
    View all