Table of contents
1.
Types of Lambda Expressions
1.1.
1. Expression Lambda
1.1.1.
Syntax of Expression Lambda
1.2.
2. Statement Lambda
1.2.1.
Syntax of Statement Lambda
2.
Example 1: Expression Lambda
2.1.
C#
3.
Example 2: Statement Lambda
3.1.
C#
4.
C# Lambda Expressions and Tuples
4.1.
C#
5.
Use of Lambda Expression
5.1.
1. Writing Easy and Simple Delegate Code
5.2.
2. Passing Parameter in Method
6.
Frequently Asked Questions
6.1.
What is the difference between lambda expression and lambda statement in C#?
6.2.
What is the benefit of lambda expression in C#?
6.3.
What are the disadvantages of lambda expressions in C#?
6.4.
Can lambda expressions use variables from outside their scope?
6.5.
Are lambda expressions in C# the same as anonymous methods?
7.
Conclusion
Last Updated: Oct 8, 2024
Easy

Lambda Expression in C#

Author Sinki Kumari
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Lambda expressions in C# are a powerful feature that allow you to write concise & readable code. They provide a way to define anonymous functions inline, without the need for a separate method declaration. Lambda expressions are commonly used with LINQ queries, event handlers & delegate invocations. 

Lambda Expression in C#

Types of Lambda Expressions

Lambda expressions in C# can be classified into two main types: 

  1. expression lambdas
  2. statement lambdas

Let's discuss both of these types in detail: 

1. Expression Lambda

An expression lambda is a concise way to define a lambda expression that consists of a single expression. It is characterized by the absence of curly braces & an explicit return statement. The syntax for an expression lambda is as follows:

Syntax of Expression Lambda

(parameters) => expression


In this syntax, the parameters represent the input parameters of the lambda expression, & the expression is the single expression that is evaluated & returned as the result of the lambda expression. The arrow => separates the parameters from the expression.

2. Statement Lambda

Unlike expression lambdas, statement lambdas allow you to write multiple statements within the lambda expression. They are enclosed in curly braces & can contain multiple lines of code. Statement lambdas are useful when you need to perform more complex operations or have multiple statements to execute. 

Syntax of Statement Lambda

(parameters) => { statements }


In this syntax, the parameters represent the input parameters of the lambda expression, & the statements are one or more C# statements that are executed when the lambda expression is invoked. The curly braces {} are used to enclose the statements.

Let's look at some examples to understand how to use lambda expressions in C#.

Example 1: Expression Lambda

  • C#

C#

// Example of an expression lambda

Func<int, int> square = x => x * x;

int result = square(5);

Console.WriteLine(result);

Output: 

25


In this example, we define an expression lambda square that takes an integer parameter x & returns the square of x. We assign the lambda expression to a Func<int, int> delegate, which represents a function that takes an integer parameter & returns an integer. We then invoke the lambda expression by calling square(5), which returns the result 25.

Example 2: Statement Lambda

  • C#

C#

// Example of a statement lambda

Action<string> greet = name =>

{

   string greeting = $"Hello, {name}!";

   Console.WriteLine(greeting);

};

greet("Rahul");

Output: 

Hello, Rahul!


In this example, we define a statement lambda greet that takes a string parameter name. Inside the lambda, we create a greeting string using string interpolation & then print the greeting to the console. We assign the lambda expression to an Action<string> delegate, which represents an action that takes a string parameter & does not return a value. We invoke the lambda expression by calling greet("Rahul"), which outputs the greeting message.

C# Lambda Expressions and Tuples

Lambda expressions in C# are concise ways to define anonymous methods using the => operator. They are often used with LINQ, delegates, and events. Tuples allow grouping multiple values into a single object. Here’s an example:

  • C#

C#

using System;

class Program {
static void Main() {
// Lambda Expression and Tuple
Func<int, int, (int sum, int diff)> calculate = (a, b) => (a + b, a - b);
var result = calculate(5, 3);
Console.WriteLine($"Sum: {result.sum}, Difference: {result.diff}");
}
}

Output:

Sum: 8, Difference: 2

Use of Lambda Expression

1. Writing Easy and Simple Delegate Code

Lambda expressions simplify writing delegate code, making it more readable and concise.

Func<int, int> square = x => x * x;
Console.WriteLine(square(5));

Output:

25

2. Passing Parameter in Method

Lambda expressions can be passed as parameters to methods, enabling inline function definitions.

void Execute(Action action) => action();
Execute(() => Console.WriteLine("Hello Lambda!"));

Output:

Hello Lambda!

Frequently Asked Questions

What is the difference between lambda expression and lambda statement in C#?

A lambda expression in C# defines a simple, single-line expression, returning a value. A lambda statement, however, can have multiple lines of code, including statements, but doesn't return a value.

What is the benefit of lambda expression in C#?

Lambda expressions simplify code by allowing concise inline function definitions, making it easier to write, read, and maintain, especially in LINQ queries and delegate usage.

What are the disadvantages of lambda expressions in C#?

Lambda expressions can reduce code readability when overused or in complex scenarios. Debugging and understanding flow can become challenging, particularly for those unfamiliar with functional programming concepts.

Can lambda expressions use variables from outside their scope?

Yes, lambda expressions can capture external variables from their enclosing scope, allowing them to use and modify these variables within their body.

Are lambda expressions in C# the same as anonymous methods?

While similar in purpose, lambda expressions are more concise and can be converted into expression trees or delegates, unlike anonymous methods which are older and typically more verbose.

Conclusion

In this article, we have learned about lambda expressions in C#. We discussed the two types of lambda expressions: expression lambdas & statement lambdas. We also saw the syntax for each type with proper examples to understand how to use them in programs. Lambda expressions provide a concise & readable way to define anonymous functions inline, making your code more expressive & easier to understand. They are particularly useful when working with LINQ queries, event handlers & delegate invocations.

You can refer to our guided paths, Contests, Test Series and Interview Experiences curated by top Industry experts.

Live masterclass