How to use Lambda Expressions in C#

C# Programming Guide
Lambda expressions (aka lambda expressions with parameters) are a powerful feature of the C# language. They allow programmers to write short, concise code that can perform complex operations. In this programming tutorial, we will examine what lambda expressions are, the benefits of lambda expressions, and how developers can write programs using lambda expressions in C#.

Looking to learn C# in a class or online course setting? We have a list of the Best Online Courses to Learn C# to help get you started.

What is a Lambda Expression in C#?

A lambda expression is represented by a block of code that can accept parameters and returns a value. Lambda expressions are analogous to anonymous methods but considerably more flexible. When using a lambda expression, you do not need to specify the input type. As a result, a lambda expression represents anonymous methods more clearly and concisely.

Lambda expressions are analogous to anonymous functions without declarations. Essentially, they are anonymous methods that lack an access specifier and a name. A lambda expression is similar to an anonymous method, but with one key difference: a lambda expression can be assigned to a variable (just like any other type of function), and it can also be passed as an argument to another function.

This makes lambda expressions perfect for writing short pieces of code or performing simple tasks within the larger codebase.

The following is the general syntax for defining a lambda expression in C#:

(parameters) -> {block of code}

What are the Benefits of Lambda Expressions?

The advantages of lambda expressions in C# include:

  • They can be used anywhere that a delegate type can be used.
  • They are useful when you want to pass an anonymous method as a parameter to a method.
  • They reduce boilerplate code and make your code more readable.
  • They can be used inline as arguments for methods like LINQ queries.
  • They can be used to implement an event handler or callback or create delegates that don’t have a name.
  • Lambda expressions can be converted into delegates, and vice versa.

How to Create a Lambda Expression in C#

Here is an example of how to create a lambda expression in C#:

Func<int, int> square = n => n * 2;
int result = square(5);

You can also create lambda expressions that can accept more than one parameter in C#, as shown in the code example below:

Func<int, int, int> multiply = (x, y) => x * y;
int result = multiply(5, 10);

The statement n=> n * 2 is a lambda expression. Here, n is an input parameter and n * 2 is the return value of the anonymous function. Note that single line lambda expressions, as shown in the preceding C# code example, do not require return statements.

In a lambda expression, the lambda operator => is specified in between the input parameters on the left of the operator and the lambda body to the right of it. While the input parameters reside on the left side of the lambda operator, the lambda body or the lambda expression’s body is on the right side.

The input parameters are specified on the left-hand side of the lambda operator =>, and on the right-hand side, there is either an expression or code block which operates with the input arguments.

Read: Best Online Courses to Learn .NET

Expression Lambda vs Statement Lambda

A lambda expression is an unnamed function that you can pass around to methods and other functions. It has a signature that specifies the types of values it returns, and any parameters it takes. A lambda expression can be of the following types:

  • Expression Lambda
  • Statement Lambda

In a lambda expression, if the expression is specified on the right side, it is called expression lambda. In an expression lambda, programmers will have expression as the body of the lambda expression, as shown in this code example:

(input-parameters) => expression

On the contrary, a statement lambda contains a statement block in its body as shown below:

(input-parameters) => {  }

The following code example illustrates how you can define a statement lambda in C#:

Action message = authorName =>
    string text = $"Author Name: {authorName}.";

Unlike the expression lambda, the statement lambda may contain several statements separated by semicolons. Here, the expression side of a lambda is a statement, which is the code block enclosed by the parentheses.

Any lambda expression may be transformed into a delegate type. The delegate type to which a lambda expression will be changed is determined by its return value and the parameters. Lambda expressions that do not return values may be transformed into Action delegate types; otherwise, they can be converted into Func delegate types.

What are the Components of a Lambda Expression in C#?

There are three main components that make up a lambda expression: the parameter list, the body, and the return type. Let’s examine each of these in detail.

Lambda Expression Parameter list

The first thing that needs to be included when creating a lambda expression is the list of parameters that it will require. This is a parameter list, which indicates what data types will be provided to the function and what their names are. These parameters can be specified using either formal or informal syntax (depending on what types of parameters are being used).

The parameter list is specified using the keyword lambda, followed by the name of the parameter (in parentheses), and then the type of that parameter (i.e., int or string).

Lambda Expression Body

The body of a lambda expression is where the actual work happens. It contains code that determines how the data from the parameter list will be used. This section can contain any C# code that you wish, and it will automatically be executed when the lambda expression is invoked (just like any other function).

In most cases, this section will simply contain a single statement (or block of statements), but it is possible to create more complex functions using lambda expressions.

Lambda Expression Return Type

The return type of a lambda expression is specified using the return keyword, and it will determine what type of value the lambda expression will return once it has completed its work. In other words, it specifies what data type will be returned by the lambda function when it’s executed.

In most cases, this will simply be void (meaning that the lambda expression will not return any values), but it is possible to create functions that return values using the return keyword.

Final Thoughts on Lambda Expressions in C#

Lambda expressions are a great new feature added in the recent versions of .NET and.NET Core. Lambda expressions may contain zero, one, or more arguments. In C#, lambda expressions may or may not accept parameters and they can be assigned to Func, Action, or Predicate delegate types.

Read more C# programming tutorials and software development guides.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Must Read