Lambda Expression in C# (With Examples)

Lambda Expression in C# (With Examples)

03 Jul 2025
Intermediate
137K Views
16 min read
Learn with an interactive course and practical hands-on labs

Best Free C# Course: Learn C# In 21 Days

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.

At compile time, all the lambda expressions are converted into anonymous methods according to the lambda expression conversion rules. It is just a new way to write anonymous methods. The left side of the lambda operator "=>" represents the arguments to the method, and the right side is the method body.

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:

Why use lambda expressions in C#

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:

Types of Lambda Expression

    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

    1. 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(); 
    2. 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); 
    3. 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.
    4. Variables defined within a lambda expression are accessible only within the scope of the lambda expression body.
    5. 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

     A lambda expression is a shorthand way to define an anonymous method (a method without a name) that can be passed as an argument to functions.

    Lambda expressions make your code shorter, more readable, and easier to maintain. They eliminate the need for separate method definitions when using delegates, LINQ, or functional programming patterns.

    Lambda expressions were introduced in C# 3.0 as part of the .NET Framework 3.5 update.

    A lambda expression is an anonymous function that is defined inline, while a normal method has a name and is defined separately in a class. Lambda expressions are generally used for short, simple logic blocks.

    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.

    GET FREE CHALLENGE

    Share Article
    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

    Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

    Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
    Live Training - Book Free Demo
    ASP.NET Core Certification Training
    05 Jul
    10:00AM - 12:00PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    Advanced Full-Stack .NET Developer with Gen AI Certification Training
    05 Jul
    10:00AM - 12:00PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    .NET Solution Architect Certification Training
    06 Jul
    08:30PM - 10:30PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    .NET Microservices Certification Training
    06 Jul
    08:30PM - 10:30PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    React Certification Training
    12 Jul
    07:00AM - 09:00AM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    Accept cookies & close this