Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Jun 11, 2024
Difficulty: Easy

Lambda Expression in C#

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

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#

In this article, we will discuss the types of lambda expressions in C#, their syntax also.

Types of Lambda Expressions

Lambda expressions in C# can be classified into two main types: expression lambdas & statement lambdas. Let's discuss both of these types: 

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

(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.

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

(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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Examples

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.

Frequently Asked Questions

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.

What is the performance impact of using lambda expressions?

Lambda expressions are generally efficient but can lead to slightly slower performance compared to inline code, especially if capturing external variables or when used extensively in tight loops.

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 on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Topics covered
1.
Introduction
2.
Types of Lambda Expressions
2.1.
Expression Lambda
2.1.1.
Syntax
2.2.
Statement Lambda
2.2.1.
Syntax
3.
Examples
3.1.
Example 1: Expression Lambda
3.2.
C#
3.3.
Example 2: Statement Lambda
3.4.
C#
4.
Frequently Asked Questions
4.1.
Can lambda expressions use variables from outside their scope?
4.2.
Are lambda expressions in C# the same as anonymous methods?
4.3.
What is the performance impact of using lambda expressions?
5.
Conclusion