A Journey to Lambda Expression: Part 2

So as of now we all know, it all started with the delegates. But delegates were just the first step Microsoft took. The  next step was anonymous methods.

Part 1 : Anonymous Methods

So what is an anonymous method? Well if I ask a student that has not prepared his homework on anonymous methods he might say:

"Anonymous Methods are methods that do not have a name."

And the strange thing is that, it is the right answer. They don't have a name. As of the last article you know that I can assign any method to the delegate instance.

del handler = fun;

And when the delegate is executed by calling handler(), it will execute fun().

But suppose I can execute the delegate without assigning it to a method. So the fun function that was defined as:

  1. public static void fun(string message)  
  2.        {  
  3.            Console.WriteLine(message);  
  4.        }  
And assigned previously as: 
  1.       del handler = fun;  
It is now replaced with this code:
  1.     del handler = delegate(string message)   
  2.     {   
  3.           Console.WriteLine(message); 
  4.       };      
And then if the code is called in the same manner as previously: 
  1.     handler("Hello World")  
The code will produce similar results.

Output

 output

So we can see that it is quite easy to implement since we don't need a method name. The complete solution code will look like:
  1. class Program  
  2. {  
  3.    public delegate void del(string msg);  
  4. tatic void Main(string[] args)  
  5.     {  
  6.        del handler = delegate(string message)   
  7.  {   
  8.                 Console.WriteLine(message);   
  9.            };  
  10.   
  11.         handler("Hello World");  
  12.         Console.ReadKey();  
  13.     }  
  14.  }  
Part 2 : Func<T, TResult> and Action <T>

Delegates have special types as well. Let's dive into those special ones. In the above scenario I defined the delegate and assign the method or anonymous method to it as:
  1. public delegate void del(string msg); 
  2. del handler = delegate(string message) { 
            Console.WriteLine(message);   
     };
  
          or
        del handler = fun; 

Where fun is the method name. So clearly we have encapsulated the method (anonymous or defined) in the delegate into our defined delegate. But you can use a Special Delegate that can encapsulate the method without explicitly declaring your delegate so you can totally avoid a declaration section as desribed as 1.

This Special Delegate is Action<T> just like (T represents Type we can use any data type here, it represents what type of Parameter it accept in this case it is string as <string> and is written in those angular braces. You can use your classes as well for T. T for Both Action <T> and Func<T, TResult> are contravariant (but TResult is Covariant),  so we can also use the types that either are specified or are less derived as parameters.)

  1. Action<string> handler = delegate(string message)  
  2.             {  
  3.                 Console.WriteLine(message);  
  4.             };  

Well you can see that I have included a delegate declaration and instance creation simultaneously and if we run the method we will see the same output that was produced earlier.

Why Action<T>? Notice the subtitle of the Section. I had written Func<T> and Action <T>, so why? Well this is a secret. Just kidding, well if we look at our delegate signature of our method or the previous delegate we can easily say it was a void type of delegate. In oher words it does not return any value. So when we don't return any value we use Action<T> and when we return a value we use Func<T>.

Now Let's see a Func<T> example.

  1. Func<intintint> handler2 = delegate(int x, int y)  
  2.     {  
  3.               return x + y;  
  4.     };  
By checking Action<T> we can easily say that in <int, int, int> there are three parameters that have been passed. But if we see the delegate definition we only see two parameters. The third one is the return type of the delegate as we have already said that Func<T, TResult> is the return value on the other hand Action<T> doesn't return any value. So we need a place where we can define what is the type of the value returned and it has been decided that it will be the last place of Func<T, TResult>. so in nutshell the last parameter is the return type. Now the complete code is as follows.
  1. class Program  
  2.  {  
  3.     public delegate void del(string msg);  
  4. static void Main(string[] args)  
  5.      {  
  6.            del handler = delegate(string message)   
  7.   {   
  8.                 Console.WriteLine(message);   
  9.            };  
  10.   
  11.   
  12.            Func<intint,int> handler2 = delegate(int x, int y)  
  13.             {  
  14.                 return x + y;  
  15.             };  
  16.   
  17.               handler("Hello World");  
  18.  Console.WriteLine("5 + 10 = " + handler2(5, 10));  
  19.             Console.ReadKey();  
  20.      }  
  21.   }  
And the output is:

 output 1
 
Well I hope you enjoy this session.

Our story will be continued in the next part. Until then au revoir.


Similar Articles