Delegates, Events and Lambda Expressions in C# – Part 2

Lambda Expressions
Lambda expressions were added to C# in the .NET 2.0 framework. A Lambda Expression is a simpler syntax that can be used for anonymous delegates. By using Lambda Expression, the resulting code in the implementation can be terse and succinct. Although it is very simple to write and use, Lambda Expressions can be daunting and difficult to understand when encountered for the first time. This is especially true because their syntax does not resemble the rest of the C# language. However, they will become clearer once they are used for few times.

The Structure of a Lambda Expression
The structure of a Lambda Expression is very simple. It is composed of a left-hand side expression and a right-hand expression separated by the Lambda Expression Operator ‘=>’. The Lambda Expression operator is required and it is what the C# pre-compiler relies upon to determine that an expression is to be processed as a Lambda Expression.

[Left-Hand Side Expression] => [Right-Hand Side Expression]

The Left-Hand Side of a Lambda Expression
The Left-Hand Side expression is an ordered set of all the parameters that are passed-in to the Lambda Expression. The ordered set is surrounded by a pair of parenthesis. Below are few simple rules concerning the Left-Hand side expression that one must abide by when declaring a Lambda Expression:

  • if a single parameter is passed in, then the parenthesis can be dropped.
  • If no parameters are passed-in, then an empty pair of parenthesis must be supplied.
  • The parameter types of the Lambda Expression are not specified. They are inferred by the compiler from the delegate declaration.
  • The scope of the the Lambda-Expression is affected by the namespace, so unique variable names should be used in the Lambda Expression declaration.

The Right-Hand Side of a Lambda Expression
The Right-Hand side expression of a Lambda Expression is identical to the body of any method in C#. However, there are few rules that one can follow to simplify a Lambda Expression further:

  • If the body of a Lambda Expression contains more than one line, then a pair of curly braces ‘{}’ is used to house the body of the expression.
  • If the body of a Lambda Expression contains a single line, then the pair of the curly braces is optional. However, if the braces are dropped, then the semi-colon at the end of the single expression must be dropped. The ‘return’ keyword is also dropped in single expressions if the delegate returns a value.

Examples of Lambda Expressions

Example1: Consider the void delegate ‘DoWork’ with a single parameter and a method body that requires multiple lines in the body declaration. In this case, the pair of parenthesis surrounding the set of parameters can be dropped for simplicity and the body of the method must be surrounded by a pair of curly braces:

public delegate void DoWork(int duration);
public class Program
{
     public static void Main(string[] args)
     {
          var doWorkHandler = new DoWork(d =>
          {
               if(d <= 0) return;
               for (int i = 0; i < d; i++)
               {
                    Console.WriteLine("Working");
               }
          });
          doWorkHandler(12);
     }
}

Example2: Consider the delegate 'DoCalculation' that takes in multiple parameters, returns a value and the body of the Lambda Expression is a single line. In this case, the pair of the curly braces can be dropped. However, by doing so, the 'return' keyword and the semi-colon must be dropped. The pair of parenthesis surrounding the parameters of the Left-Hand side expression are mandatory.

public delegate int DoCalculation(int val1, int val2);

public class Program
{
     public static void Main(string[] args)
     {
          var doCalculationHandler = new DoCalculation((val1, val2) => val1 + val2);

          var sum = doCalculationHandler(2, 10);
          Console.WriteLine(sum);
     }
}

Example3: Consider the delegate 'ProcessTask' that takes in no parameters and returns a value. The body of the expression contains more than one line. In this case, a pair of empty parenthesis must be specified on the left-hand side expression to indicate that no parameters are passed in.

public delegate bool ProcessTask();

public class Program
{
     public static void Main(string[] args)
     {
          var processTaskHandler = new ProcessTask(() =>
          {
               Console.WriteLine("Do Some Work");
               return true;
          });

          processTaskHandler();
     }
}

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *