04
JulLambda Expression in C# (With Examples)
Lambda expression in C# represents an anonymous method (a method without a name) which is used to create small functions that can be passed as arguments to methods, especially for delegates, LINQ queries, and event handlers. The concept of lambda expression was introduced in C# 3.0.
In this C# tutorial , you will explore lambda expressions in C#, the syntax of lambda expressions, an example of a lambda expression in C#, why we use lambda expressions in C#, Types of Lambda expressions, and Features of Lambda expressions. Let’s dive into it
What is a Lambda Expression in C#?
A lambda expression in C# is a way to define an anonymous function (a function without a name) using a simple and clear syntax.It is very useful when you want to pass short blocks of code (functions) as arguments to methods, for example, in LINQ, delegates, and event handlers.
Lambda expression Syntax
(parameters) => expression-or-statement-block
Explanation:
- => is called the lambda operator.
- On the left side: the input parameters.
- On the right side: the expression (for returning a value) or a block of statements.
Example of Lambda Expression C#
Here is a simple example of using a lambda expression in C#:
func<int, int>square= x => x * x;
console.WriteLine(square(5)); // Output: 25
Code Explanation:
- func<int, int> means a function that takes an int and returns an int.
- x => x * x is a lambda expression.
Why use lambda expressions in C#?
We use lambda expressions in C# to write more concise, readable, and flexible code, especially when working with collections, LINQ, delegates, or events.
Here are the main reasons why:
1. Shorter Code (No Need to Write Full Methods)
- Instead of writing a whole method, you can quickly pass logic as a parameter.
2. Used with LINQ
- Lambda expressions are the backbone of LINQ queries in C#. They allow you to filter, project, and manipulate data collections.
3. Pass Functions as Arguments
- Lambda makes it easy to pass a function as a parameter to another method (using delegates like Func<>, Action<>, Predicate<>).
4. Anonymous Functions
- You don’t have to name or separately define the function — it’s written right where it’s needed.
5. Simpler Event Handling
- You can handle events inline without creating a separate method.
Types of Lambda Expression in C#
C# lambda expressions can be categorized mainly by how they are written and how they are used. Here are the main types of lambda expressions:
1.) Statement Lambda
- Statement lambda has a statement block on the right side of the lambda operator "=>".
x => { return x * x; };
2.) Expression Lambda
- Expression lambda has only an expression (no return statement or curly braces), on the right side of the lambda operator "=>".
x => x * x; // here x*x is expression
3.) Lambda with No Parameters
- Syntax: () => expression_or_block
- Can be used when no input parameters are required.
- Example:
Func<string> greet = () => "Hello!";
Console.WriteLine(greet()); // Output: Hello!
4.) Lambda with Multiple Parameters
- Syntax: (param1, param2) => expression_or_block
- Example:
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 4)); // Output: 7
5.) Async Lambda (Asynchronous Lambda)
- Used when you want to write asynchronous code inside the lambda.
- Example:
Func<Task> asyncLambda = async () =>
{
await Task.Delay(1000);
Console.WriteLine("Done!");
};
Read More: C# Interview Questions And Answers
Features of the Lambda Expression
- Lambda expressions themselves do not have type. There is no concept of a lambda expression in the CLR.
// ERROR: Operator '.' cannot be applied to // operand of type 'lambda expression' Type type = ((int x) => x).ToString();
- A lambda expression cannot be assigned to an implicitly typed local variable since the lambda expressions do not have type.
// ERROR: Cannot assign lambda expression to an // implicitly typed local variable var thing = (x => x);
- Jump statements (break, goto, continue) are not allowed within anonymous method/lambda expression. Similarly, you cannot jump into the lambda expression/ anonymous method from outside.
- Variables defined within a lambda expression are accessible only within the scope of the lambda expression body.
- Lambda expressions are used generally with the Func and Action delegates. our earlier expression can be written as follows:
Func sqr = x => x * x;
Anonymous method with Lambda and Delegate in C# Compiler
class Program
{
//delegate for representing anonymous method
delegate int del(int x, int y);
static void Main(string[] args)
{
//anonymous method using expression lambda
del d1 = (x, y) => x * y;
// or (int x, int y) => x * y;
//anonymous method using statement lambda
del d2 = (x, y) => { return x * y; };
// or (int x, int y) => { return x * y; };
//anonymous method using delegate keyword
del d3 = delegate(int x, int y) { return x * y; };
int z1 = d1(2, 3);
int z2 = d2(3, 3);
int z3 = d3(4, 3);
Console.WriteLine(z1);
Console.WriteLine(z2);
Console.WriteLine(z3);
}
}
Output
6
9
12
What is LINQ with Lambda Expression in C#?
- LINQ (Language Integrated Query) lets you query collections in C#.
- Lambda expressions provide a short and clear way to define the logic used in the query.
- The combination — LINQ + Lambda Expression is very powerful for working with data collections.
Example of LINQ in C Sharp:
using System;
using System.Collections.Generic;
using System.Linq;
class Product
{
public string Name { get; set; }
public int Price { get; set; }
}
class Program
{
static void Main()
{
// Integer list for LINQ examples
List<int> numbers = new List<int> { 2, 5, 8, 10, 15, 20 };
Console.WriteLine("Even Numbers:");
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var num in evenNumbers)
Console.WriteLine(num);
Console.WriteLine("Squares of Numbers:");
var squares = numbers.Select(n => n * n);
foreach (var s in squares)
Console.WriteLine(s);
Console.WriteLine("Numbers Greater Than 10:");
var greaterThanTen = numbers.Where(n => n > 10);
foreach (var n in greaterThanTen)
Console.WriteLine(n);
// List of Products for object-based LINQ
List<Product> products = new List<Product>
{
new Product { Name = "Book", Price = 200 },
new Product { Name = "Pen", Price = 50 },
new Product { Name = "Bag", Price = 800 }
};
Console.WriteLine("Expensive Products (Price > 100):");
var expensiveProducts = products
.Where(p => p.Price > 100)
.Select(p => p.Name);
foreach (var name in expensiveProducts)
Console.WriteLine(name);
}
}
Output:
Even Numbers:
2
8
10
20
Squares of Numbers:
4
25
64
100
225
400
Numbers Greater Than 10:
15
20
Expensive Products (Price > 100):
Book
Bag
Lambda expression as an Event Handler
<form id="form1" runat="server">
<div align="center">
<h2>Anonymous Method Example</h2>
<br />
<asp:Label ID="lblmsg" runat="server" ForeColor="Green" Font-Bold="true"></asp:Label>
<br /><br />
<asp:Button ID="btnReset" runat="server" Text="Reset" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
// Click Event handler using Regular method
btnReset.Click += ClickEvent;
// Click Event handler using Anonymous method
btnSubmit.Click += delegate { lblmsg.Text="Submit Button clicked using Anonymous method"; };
// Click Event handler using Lamda expression
btnCancel.Click += (senderobj, eventobj) => { lblmsg.Text = "Cancel Button clicked using Lambda expression"; };
}
protected void ClickEvent(object sender, EventArgs e)
{
lblmsg.Text="Reset Button clicked using Regular method";
}
Conclusion
Lambda expressions are an essential feature of modern C# programming, enabling developers to write more concise, readable, and flexible code. Whether you are working with LINQ queries, handling events, or passing functions as parameters, lambda expressions simplify the process by eliminating the need for verbose method declarations.
By understanding the different types of lambda expressions and how to apply them effectively, you can greatly enhance the quality and maintainability of your C# applications. Explore Free C# Full Course — and gain the expertise to build powerful, professional-grade C# applications today!
FAQs
Take our Csharp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.