Anonymous Methods in C#

Anonymous Methods

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body.

You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.

We will create a demo application to first do some stuff without anonymous methods. And later we will be using anonymous methods to get the same functionality and will check the difference between the two.

Without Anonymous Method

Write the following code in a console application.

  1. delegate int Mydel(int a, int b);  
  2.   
  3.   class Program  
  4.   {  
  5.       public static int Add(int x,int y)  
  6.       {  
  7.           int sum = x + y;           
  8.           return sum;  
  9.       }  
  10.       static void Main(string[] args)  
  11.       {            
  12.          Mydel obj = Add;             
  13.          int result= obj.Invoke(12, 13);  
  14.          Console.WriteLine("The sum is : " + result);  
  15.          Console.ReadLine();  
  16.       }  
  17.   }  

In the preceding sample we have an Add method that takes two arguments of integer type. We have defined a delegate that holds the reference of the Add method.

Now when we invoke this delegate and pass the values to it, it calls the add method that returns the sum of the input parameters and displays it on the output window.

Let us check the output of this code now.



Using Anonymous Method

Now let us suppose if the number of arguments increase at some given point of time, then would we again add a new argument and would passing it be feasible each and every time? Instead of doing it again and again we can use anonymous functions.

We will now modify the preceding sample using an Anonymous function. Write the following code in a console application:

  1. delegate int Mydel(int a,int b);  
  2.   
  3.    class Program  
  4.    {  
  5.        static void Main(string[] args)  
  6.        {  
  7.            Mydel del = delegate(int x, int y)  
  8.            {  
  9.                return x + y;  
  10.            };  
  11.            int result=del.Invoke(12,13);   
  12.            Console.WriteLine(result);   
  13.            Console.ReadLine();    
  14.        }   
  15.      }  
As we can see, the preceding program has an anonymous method defined that directly contains the code for adding the numbers. So using anonymous methods we can reduce the lines of code (since we have omitted the Add function in this case).

Let us check the output of this program now.


Similar Articles