The Anonymous Methods and Lambda Expressions in .NET

The purpose of this article is to provide the basic idea of Anonymous methods and Lambda expressions in C#.

Anonymous Method

An anonymous method is an unnamed method that contains only a body without a name or identifier and it is invoked by the delegates. An anonymous method is referenced or associated with a delegate and it cannot be invoked explicitly or directly without using a delegate. The body of the anonymous method is surrounded by curly braces and it contains the inline code. The anonymous method is used when we have a small task or operation and we want to do it inline. An anonymous method is similar to a named method but the main difference is that a named method has a specified name, an access modifier, a return type, a parameters list that contains zero or more parameters and a body that contains a block of code whereas an anonymous method is an unnamed method that has no name or identifier, no access modifier and no return type and its declaration always starts from the keyword delegate followed by the parameters list and the method body.

The parameters list of an anonymous method may contain zero or more parameters and they are surrounded by small braces. An anonymous method does not need to specify its return type but it allows us to return a value using the return statement. A named method can be invoked directly or explicitly by simply calling its name while an anonymous method cannot be invoked directly or explicitly like a named method but it can be invoked implicitly using a delegate. To invoke an anonymous method, an instance of the delegate is declared and the anonymous method is referenced or associated with it. When an anonymous method is referenced or associated with an instance of the delegate then we invoke it by calling that instance and pass values to its parameters if it takes parameters.

An anonymous method can be referenced or associated with an instance of the delegate by assigning the anonymous method to it as a parameter. When an anonymous method is assigned to an instance of the delegate as a parameter, the instance of the delegate stores its memory address and the method is referenced or associated with it.

A delegate can reference and invoke an anonymous method that has the matching parameters with it. It means that the parameters of the delegate and the parameters of the referenced or associated anonymous method must be the same. For example, if an anonymous method does not take any parameter then it can be referenced and invoked by an instance of a delegate that does not take any parameter. Similarly, if an anonymous method takes a single integer parameter then we must declare an instance of the delegate that takes a single integer parameter and so on. The following is the general syntax to declare a parameter-less anonymous method:

The C# Syntax

  1. instDelegate = delegate() {-Body of the anonymous method-};  
  2.   
  3. Or  
  4. instDelegate = delegate()  
  5. {  
  6. [-Body of the anonymous Method-]  
  7. }; 

In the preceding declaration, the instDelegate is an instance of the parameter-less delegate that does not take any parameter and it references a parameter-less anonymous method. The [-Body of the Anonymous Method-] indicates the body of the anonymous method that contains the inline code. The following is the general syntax to declare a parameterized anonymous method that takes the specified number of parameters.

The C# Syntax

  1. instDelegate = delegate(ParametersList) {[-Body of Method-]};  
  2.   
  3. Or  
  4.   
  5. instDelegate = delegate(ParametersList)  
  6. {  
  7. [-Body of Method-]  
  8. }; 

In the preceding declaration, the instDelegate is an instance of the parameterized delegate that takes one or more parameters depending on the method it references and invokes. For example, if the anonymous method takes a single integer parameter then it must take a single integer parameter, similarly if an anonymous method takes one integer and one float parameter then it must take one integer and one float parameters and so on. The ParametersList indicates a list of parameters of the anonymous method that contains one or more parameters. The [-Body of Method-] indicates the body of the anonymous method that contains the inline code.

Program # 1

Write a program that displays a message on the screen using a parameter-less anonymous method.

The C# Program

  1. using System;  
  2.   
  3. namespace ProgramNamespace  
  4. {  
  5. //Define a delegate reference type that references or associates a //parameter-less anonymous method having no parameters and //does not return value  
  6.   
  7. delegate void MyDelegate();  
  8.   
  9. public class MainProgramClass  
  10. {  
  11. public static void Main()  
  12. {  
  13. //Declare an instance of the delegate MyDelegate reference type  
  14.   
  15. MyDelegate instDelegate;  
  16.   
  17. //References or associates the parameter-less anonymous method //with the instance instDelegate of the delegate by assigning the //anonymous method to it as parameter using a single line //assignmnet  
  18.   
  19. instDelegate = delegate() { Console.WriteLine("Hello"); };  
  20.   
  21. //We can also reference or associate the anonymous method with //the instance instDelegate of the dcelegate by assigning the //anonymous method to it as parameter using the multiple lines //assignment  
  22.   
  23. instDelegate = delegate()  
  24. {  
  25. Console.WriteLine("Hello");  
  26. };  
  27.   
  28. //Invoke the anonymous method that displays a message on the //screen  
  29.   
  30. instDelegate();  
  31.   
  32. Console.WriteLine("Press any key to exit ");  
  33. Console.ReadKey();  
  34. }  
  35. }  

The preceding program displays Hello on the screen using an anonymous method. In the program we defined a delegate reference type MyDelegate that has no parameters and does not return value. In the main method of the program we declared an instance instDelegate of the delegate reference type MyDelegate and it is instantiated by assigning an anonymous method that has no parameters and does not return any value. The instance instDelegate of MyDelegate reference type is then used and invokes the referenced anonymous method.

Program # 2

Write a program that adds two integer values using an anonymous method. The anonymous method takes two integer parameters and returns their sum to the calling point.

The C# Program

  1. using System;  
  2.   
  3. namespace ProgramNamespace  
  4. {  
  5. //Define a Delegate reference type that references or associates an //anonymous method having two integer parameters and return an //integer value  
  6.   
  7. delegate int MyDelegate(int x, int y);  
  8.   
  9. public class MainProgramClass  
  10. {  
  11. public static void Main()  
  12. {  
  13. //Declare an instance of the delegate MyDelegate reference type  
  14.   
  15. MyDelegate instDelegate;  
  16.   
  17. //References or associates the parameterized anonymous method //with the instance instDelegate of the delegate by assigning the //anonymous method to it as parameter using a single line //assignmnet  
  18.   
  19. instDelegate = delegate(int x, int y) {return x + y;};  
  20.   
  21. //We can also reference or associate the anonymous method with //the instance insDelegate by assigning the anonymous metho to it //as parameter using the multiple lines assignment  
  22.   
  23. instDelegate = delegate(int x, int y)  
  24. {  
  25. return x + y;  
  26. };  
  27.   
  28. //Invoke the anonymous method and pass two integer values to it //and declare an integer variable to store the result of the //anonymous method  
  29.   
  30. int result = instDelegate(2, 3);  
  31.   
  32. //Display the result of the anonymous method  
  33. Console.WriteLine("The sum of two values = " + result);  
  34.   
  35. Console.WriteLine("Press any key to exit ");  
  36. Console.ReadKey();  
  37. }  
  38. }  

The Lambda Expression

A Lambda expression is a simplified form of an anonymous method that is used to write an anonymous method without its declaration in the form of an expression. It divides an anonymous method into two parts and makes an expression by placing an operator between them that is called the Lambda operator. The declaration of an anonymous method always starts from a keyword delegate followed by a parameters list and its body. The parameters list of an anonymous method may contain zero or more parameters and each parameter requires its data type specification. For example, if an anonymous method takes one or more parameters then we must specify the data type of each parameter. A Lambda Expression reduces a keyword delegate and the data type specifications of the parameters and it allows us to write an anonymous method without the use of the keyword delegate and the data type specifications of its parameters. The Lambda Expression allows us an option to declare all the input parameters of an anonymous method with their data type specifications or simply provide the names of the input parameters without their data type specifications. The compiler automatically manages the data types of the input parameters from the usage.

A Lambda expression contains two parts separated by an operator that is called the Lambda Operator. The Lambda operator is the combination of an equal operator and a greater than operator and it is represented as =>. The Lambda operator is placed between the two parts of the Lambda Expression in which the left side part of the Lambda Expression indicates the input parameters list of the anonymous method surrounded by small braces and the right side part of the Lambda Expression indicates the body of the anonymous method. The body of an anonymous method may contain a single or multiple statements. If the body of an anonymous method contains a single statement then usually it is written on the same line with the Lambda operator and if the body of an anonymous method contains multiple statements then it is surrounded by the curly braces { } just like an anonymous method.

To write an anonymous method using a Lambda Expression, it divides the anonymous method into two parts such as a parameters list and body of the anonymous method. The left side part of the Lambda Expression takes the input parameters of an anonymous method without its parameters data type specifications. It just takes the names of the input parameters and there is no need to specify their data types because the compiler automatically infers the data types of the input parameters from the usage. The right side part of the Lambda Expression takes the body of the anonymous method. The Lambda Expression is introduced in C# 3.0. the following is the general syntax to declare a Lambda Expression:

  1. ([InputParametersList]) => {[BodyOfAnonymousMethod]}; 

The preceding syntax is a general syntax of a Lambda Expression that writes an anonymous method in two parts and makes an expression. The left side part of the Lambda Expression is ([ParametersList]) that indicates the number of input parameters of an anonymous method, the sign => indicates the Lambda operator and the right side part of the Lambda Expression is [BodyOfAnonymousMethod] that indicates the body of an anonymous method. If the body of an anonymous method contains more than one statement then the body is surrounded by curly braces and the preceding syntax can be written as:

  1. ([InputParametersList]) => { [BodyOfAnonymousMethod] }; 

Or

  1. ([ParametersList]) =>  
  2. {  
  3. BodyOfAnonymousMethod  
  4. }; 

The Benefits of using Lambda Expression

A Lambda Expression is the best choice to use to reduce the block of code and makes it easier and understandable. It reduces the complexity of an anonymous method and makes it simpler and shorter. A Lambda Expression reduces the delegate keyword from the declaration of an anonymous method and the data type specifications of its parameters. The main use of a Lambda Expression is to access the LINQ. If we want to access the LINQ in our program code then the Lambda Expression is a best choice to access the LINQ.

Program # 3

Write a program that displays a message on the screen using a parameter-less anonymous method. The anonymous method uses a Lambda Expression.

The C# Program

  1. using System;  
  2.   
  3. namespace ProgramNamespace  
  4. {  
  5. //Define a delegate reference type that references or associates a //parameter-less anonymous method in the form of a Lambda //Expression having no parameters and does not return value  
  6.   
  7. delegate void MyDelegate();  
  8.   
  9. public class MainProgramClass  
  10. {  
  11. public static void Main()  
  12. {  
  13. //Declare an instance of the delegate MyDelegate reference type  
  14.   
  15. MyDelegate instDelegate;  
  16.   
  17. //References the Lambda Expression with the instance //instDelegate of the delegate  
  18.   
  19. instDelegate = () => { Console.WriteLine("Hello"); };  
  20.   
  21. //Invoke the Lambda Expression using the instance of the delegate  
  22.   
  23. instDelegate();  
  24.   
  25. Console.WriteLine("Press any key to exit ");  
  26. Console.ReadKey();  
  27. }  
  28. }  

Up Next
    Ebook Download
    View all
    Learn
    View all