C Sharp Anonymous Functions

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# Anonymous Functions

Anonymous function is a type of function that does not has name. In other words, we can say that a function without name is known as anonymous function.

In C#, there are two types of anonymous functions:

  • Lambda Expressions
  • Anonymous Methods

C# Lambda Expressions

Lambda expression is an anonymous function which we can use to create delegates. We can use lambda expression to create local functions that can be passed as an argument. It is also helpful to write LINQ queries.

C# Lambda Expression Syntax

 
  1. (input-parameters) => expression  

Example

 
  1. using System;  
  2. namespace LambdaExpressions  
  3. {  
  4.     class Program  
  5.     {  
  6.         delegate int Square(int num);  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Square GetSquare = x => x * x;  
  10.             int j = GetSquare(5);    
  11.             Console.WriteLine("Square: "+j);  
  12.         }  
  13.     }  
  14. }  

Output:

Square: 25

C# Anonymous Methods

Anonymous method provides the same functionality as lambda expression, except that it allows us to omit parameter list. Let see an example.

Example

 
  1. using System;  
  2. namespace AnonymousMethods  
  3. {  
  4.     class Program  
  5.     {  
  6.         public delegate void AnonymousFun();  
  7.         static void Main(string[] args)  
  8.         {  
  9.             AnonymousFun fun = delegate () {  
  10.                 Console.WriteLine("This is anonymous function");  
  11.             };  
  12.             fun();  
  13.         }  
  14.     }  
  15. }  

Output:

This is anonymous function