Mohammed Omar's Blog

Just another WordPress.com site

Tag Archives: anonymous methods

Evolution Of Delegates Part 2

     So i assume you have read Evolution Of Delegates Part 1, any way lets start off by explaining anonymous delegate   

Anonymous Delegates   

     Anonymous delegates the ability to declare a delegate and the method it points to inline without the need to declare the method separately, well that sound awesome but sure it has  its advantages and disadvantages, like one of the disadvantages is you can not reuse that method in other places any way im sure you can come up with some other disadvantages ;)… so lets jump to how do we implement anonymous delegates?   

Consider this delegate:   

public delegate void MyDelegate(int left, int right);

And this method:   

        public static void sum(int left, int right)
        {
            Console.WriteLine(left + right);
        }

Usually we register it this method with that delegate like that   

      MyDelegate del = new MyDelegate(sum);
      //or using Method group conversion
      del += sum;

Now we want to register same implementation of  this method to that delegate without declaring the method how do we do that ? simple 3 steps:   

1-first copy the whole method and assign it to the delegate object:     

      mydelegate del = public void Sum(int left, int right)
			           {
				             Console.WriteLine(left + right);
			           }; 

2- Delete the method scope and return:

      mydelegate del = Sum(int left, int right)
			     {
				        Console.WriteLine(left + right);
			     }; 

3-Replace the method name with the keyword “delegate”:  

      mydelegate del = delegate(int left, int right)
                         {
                              Console.WriteLine(left + right);
                         }; 

guess what ! you made it now your project can compile no problem !, but wait ! there are some rules you have to know about anonymos delegates:

  1. Anonymous delegate can not access Ref/Out parameters in its defining method.
  2. Anonymous delegate cant declare a variable with the same name as a variable in its defining method.
  3. Anonymous delegate can declare a variable with the same name as member in its class but that gonna hide the outer variable.
  4. prolly there are some more im missing !.

any way in the next post im gonna be talking shortly about the Yield keyword and then we are gonna make a sample which mix all the previous features of C# then come up with how lambda expression and linq came out of all this ! thanks and see you later in the next post….

Advertisements