Lambda Expressions in C#

Rumman Ansari   Software Engineer   2024-09-21 06:07:43   28  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

What is Lambda expressions?

Lambda expressions in C# are a concise way to represent anonymous methods (i.e., methods without a name). They allow you to create small blocks of code that can be passed around like variables, particularly useful in situations such as LINQ queries, delegates, or event handlers.

In essence, lambda expressions make your code more readable and compact, especially when working with collections or functional programming patterns.


Key Advantages of Lambda Expressions

  1. Concise Code: Instead of defining a full method or delegate, lambdas provide a shorthand way to implement functionality in one line.
  2. Improved Readability: In many cases, lambdas make code easier to understand by keeping the logic compact and in-place.
  3. Functional Programming: They are ideal for scenarios where you want to use functional programming techniques, such as passing functions as parameters, chaining methods, or composing complex expressions.

Syntax of Lambda Expressions

The syntax for a lambda expression is as follows:


(parameters) => expression

Or if the body has multiple statements:


(parameters) => { statements }

Parts of a Lambda Expression

  1. Parameters: The parameters that the lambda expression takes, enclosed in parentheses (). This is similar to the parameters of a method.
  2. Arrow operator (=>): Separates the parameters from the expression or the block of code.
  3. Expression or Block of Code: The code that gets executed when the lambda expression is called.

Example of a Simple Lambda Expression

Here's a simple example that takes one input and returns its square:


Func<int, int> square = x => x * 2;
Console.WriteLine(square(5));  // Output: 10

In this example:

  • Func<int, int> represents a delegate that takes an integer and returns an integer.
  • x => x * 2 is the lambda expression:
    • x: Input parameter.
    • x * 2: Expression to compute and return the result.

Detailed Example: Lambda with Multiple Parameters

You can also have lambda expressions with multiple parameters:


Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 4));  // Output: 7

This example:

  • Takes two integer parameters a and b.
  • The lambda a + b adds the two numbers and returns the result.

Lambda Expression with a Block of Code

If you need more than a single expression, you can use a block of code inside the lambda:


Func<int, int> square = x => {
    Console.WriteLine("Calculating square...");
    return x * x;
};
Console.WriteLine(square(5));  // Output: Calculating square... 25

In this example:

  • The lambda body is a block {} that allows for multiple statements.
  • We added a Console.WriteLine() inside the lambda before returning the square of the input.

Use Cases of Lambda Expressions

Lambda expressions are often used in conjunction with delegates and functional interfaces like Func and Action. A few common use cases include:

1. LINQ Queries

Lambda expressions are heavily used in LINQ (Language Integrated Query) for querying collections:


int[] numbers = { 1, 2, 3, 4, 5 };
var evens = numbers.Where(x => x % 2 == 0).ToList();

foreach (var num in evens)
    Console.WriteLine(num);  // Output: 2, 4

Here:

  • x => x % 2 == 0 is a lambda expression that returns true for even numbers.
  • It filters the numbers to get only the even ones.

2. Delegates

You can pass a lambda expression to a delegate:


Action<string> greet = name => Console.WriteLine($"Hello, {name}!");
greet("John");  // Output: Hello, John!

Here:

  • greet is a delegate of type Action<string>, and the lambda name => Console.WriteLine(...) is passed to it.

3. Event Handlers

Lambda expressions can be used in event handling:


button.Click += (sender, e) => { Console.WriteLine("Button clicked!"); };


Full Example of a Lambda in C#

Here’s a complete example where we use a lambda expression to filter a list:


using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        // Lambda expression to filter even numbers
        var evenNumbers = numbers.Where(x => x % 2 == 0).ToList();

        foreach (var num in evenNumbers)
        {
            Console.WriteLine(num);  // Output: 2, 4
        }
    }
}


Conclusion

  • Lambda expressions in C# offer a powerful and concise way to write inline code logic, particularly useful for delegates, LINQ queries, and event handling.
  • They improve readability, reduce boilerplate, and bring a functional programming approach to C#.