Mohammed Omar's Blog

Just another WordPress.com site

Monthly Archives: September 2010

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….

Evolution Of Delegates Part 1

What is delegate any way ?

             remember the topic called pointer to function in C/C++ you used to hate ? well its back again !, but this time Microsoft made a good job maknig this easier and more safe and secure.
             back in dark ages function pointers used to be defined as variable which points to address of a function, part of the fact that in C/C++ you had to manage memory your self it was kind of dangrous when you work with pointers in general, any way that is all changed in .net , now Delegates (reference to functions) are defined as

Type safe object which points to an execution of a method

            so how you define a delegate to point to a method ?

 consider this method:

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

      in order to define a delegate which points to this function you do this steps :

  1. Clear Method Implementation.
  2. Clear static keyword.
  3. add the keyword “delegate” after method scope “public”.
  4. Add ; at the end.
  5. change sum to delegate name, (i will call it mydelegate).
public delegate void MyDelegate(int left, int right);

     Congratulation you just declared your first delegate!, any way you have to remember that to define a delegate you have to provide 3 piece of information of the method the delegate will point to:

  1. return type “in this example its void”.
  2. delegate name “Mydelegate”.
  3. Parameters “(int left, int right)”.

     Now what really happened behind the scene when you did that ?

By declaring Mydelegate you just defined a delegate class type which inherits from “System.MultiCastDelegate”, which in turns provide you with the ability to register multi methods to your delegate and provide you with a list of all the methods registered to your delegate!, in order to register a method to your delegate you have to create an object of your delegate and pass method name as a parameter to the constructor:

      MyDelegate del = new MyDelegate(sum);

Now to call the method by referencing the delegate you do the following:

      del(2, 3);

now if you want to register one more methods lets say this method:

 public static void Multiplay(int left, int right)
        {
            Console.WriteLine(left * right);
        }

You register it as following:

 del += Multiplay;

Notice here we used a feature called Method Group Conversion which allow you to assign a method directly to a delegate for registering it. I would like to stress something in here which is when you register a Method to a delegate you actually registering the execution of that method, that way if you registered a method 3 times that means the execution of that methods is going to happen 3 times, this is because every time your register a methods by assigning it using the operator += you actually call a IL method which is Combine which combine the method IL to the IL this delegate is pointing to!

To Be Continued….

Path 2 Expression Trees

In the beginning!      
               It all started with LINQ2SQL and the need for making a good Web Application Architecture, making loosely coupled layers and separating concerns, the fact that we need to transfer lambda expressions between layers to support fully function interfaces for search made me start thinking about how LINQ2SQL really works, to be honest i never thought i would be digging into Expression treeS i thought its all about just making methods which expect Lambda Expression and passing them through layers, here is some facts i went through:   

  • I need away to transfer Lambda Expression between layers.
  • Since layers should`nt know nothing about upper layers i need to find away to translate lambda expression parameters types to fit the need of lower layers as long as it travel deeper and deeper through layers.
  • I needed to support MemberAccess expressions, Method Calls, almost all kind of Expression Types to allow fully functional Lambda expression.

                     So any way after i made all this possible i decided to start a learning Path toward the Expression Trees and i decided to blog that path, i will start posting almost everything i needed to learn to get to Expression Trees and then im willing to post everything i learn about Expression trees, so far in the next Posts i will be writing the following topics in this order:    

  1. Delegates.
  2. Anonymous Delegates.
  3. Lambda Expressions.
  4. evolution of Predicate (Func/Action).
  5. ExpressionTrees.

              I would also like to make it clear that most of the info im going to provide i learned by searching and by other articles, but i never find any place that i could learn about expression trees from A to Z,  that is why i thought of starting this series of posts, hoping it will give developers who wants to learn about Expression Tree what i couldnt find any where.  

see you in several coming Posts.