sunshine



Anonymous Methods in C#

What is an Anonymous Method:

In order to understand anonymous methods, you should have a good understanding of delegates. If you don’t please read the article on Delegates.

I would define anonymous Methods as

Anonymous methods are methods without a name accessed via delegates.There are 2 kinds of anonymous Methods. They are

1. Anonymous methods, introduced with .NET 2.0 ( This article explains anonymous methods)

2. Lambda Expressions, introduced with .NET 3.0( This is explained in a separate article)

Basically delegates abstract a set of code. Anonymous methods takes it a step ahead. You don’t need to provide a name to the set of code. Just give the body.

Look at the pseudo code below from delegates article.

MathCalculations()

{

  int y = GenericCalculation(Square,10);

  int z = GenericCalculation(Cube,10);

  int a = GenericCalculation(SquareRoot,10);

}

int GenericCalculation( Calc Generic, int x )

{ 

  return Calc(x);

}

Now the same can be replaced by this.

MathCalculations()

{

  int y = GenericCalculation(delegate(int x) {return x*x;},10);

  int z = GenericCalculation(delegate(int x) {return x*x*x;},10);

  int a = GenericCalculation(delegate(int x) {return Sqrt(x);},10);

}

}

We just provided inline definition for each of the Method instead of defining them. So

delegate(int x) {return x*x;}

is an anonymous Method

Following is the code from our delegates sample

class Program

{

     public delegate int Calc(int x);  //This will hold the reference to a Method

     static void Main(string[] args)

     {

            Program p = new Program();

            Calc generic = p.Square;//Assign the delegate with the reference of Square Method

            int square = p.GenericCalculation(generic, 5);//Assign the delegate with the reference of Square Method

            Console.WriteLine("Square of 5 is {0}", square);

            generic = p.Cube; //Assign the delegate with the reference of Cube Method

            int cube = p.GenericCalculation(generic, 5); //Call the cube Method via the delegate

            Console.WriteLine("Cube of 5 is {0}", cube);

            Console.ReadKey();



     }

     int GenericCalculation( Calc Generic, int x )

     {

            return Generic(x);

     }

     int Square(int x)

     {

            return x * x;

     }

     int Cube(int x)

     {

           return x * x * x;

     }

}

Below is the same code rewritten with anonymous methods

class Program

    {

        static void Main(string[] args)

        {

            Program p = new Program();

            int square = p.GenericCalculation(delegate(int x) { return x * x; }, 5);

            Console.WriteLine("Square of 5 is {0}", square);

            int cube = p.GenericCalculation(delegate(int x) { return x * x * x; }, 5); 

            Console.WriteLine("Cube of 5 is {0}", cube);

            Console.ReadKey();



        }

        int GenericCalculation( Calc Generic, int x )

        {

            return Generic(x);

        }

    }

As you can see you can completely avoid the declaration needed for a delegate type and then some assignment operations.

One thing I like about anonymous methods is their ability to access objects.

SomeObject some = new SomeObject( iSomeMoreInterface);

SomeCommand.Handler = 

delegate() { 

             if(some.status ==Status.Completed )

         {

                   ......

         }

       }



If it was a traditional event handler and that class is in a different context, then you need to pass the “some” object to the handler. With anonymous Method you have straight access.

In the above scenario the object “some” is called an “out” parameter to the delegate. The reference to the outer variable “some” is said to be captured when delegate is created. So the “some” object will be in scope until the delegate is garabage collected. There are a few rule with Anonymous methods. They are

1. Goto, break, continue are not allowed.

2. Anonymous methods are not allowed on the leftside of an operator.

3. No unsafe code is allowed inside anonymous method.

We offer one on one C# training,SQL training,WCF training,WPF training,WinForms training, MVC training, ASP.NET training, Ajax & Javascript training. Please see the contacts page