0
0
C Sharp (C#)programming~5 mins

Lambda expression syntax in C Sharp (C#)

Choose your learning style9 modes available
Introduction
Lambda expressions let you write small, quick functions without naming them. They make your code shorter and easier to read.
When you want to quickly define a function to pass as an argument.
When filtering or transforming lists or collections.
When writing event handlers or callbacks.
When you want to write simple functions inline without cluttering your code.
Syntax
C Sharp (C#)
(input_parameters) => expression_or_statement_block
If there is only one input parameter, parentheses around it are optional.
The right side can be a single expression or a block of statements inside { }.
Examples
A lambda that takes one input x and returns x squared.
C Sharp (C#)
x => x * x
A lambda that takes two inputs and returns their sum.
C Sharp (C#)
(x, y) => x + y
A lambda with explicit types and a statement block that returns the difference.
C Sharp (C#)
(int x, int y) => { return x - y; }
A lambda with no input parameters that prints a message.
C Sharp (C#)
() => Console.WriteLine("Hello")
Sample Program
This program uses lambda expressions to filter even numbers and to square each number in a list. It shows how lambdas make working with collections easy and clear.
C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

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

        // Use lambda to filter even numbers
        var evens = numbers.Where(n => n % 2 == 0);

        Console.WriteLine("Even numbers:");
        foreach (var num in evens)
        {
            Console.WriteLine(num);
        }

        // Use lambda to square numbers
        var squares = numbers.Select(x => x * x);

        Console.WriteLine("Squares:");
        foreach (var sq in squares)
        {
            Console.WriteLine(sq);
        }
    }
}
OutputSuccess
Important Notes
Lambdas can capture variables from the surrounding code, which is called a closure.
Use lambdas to keep your code short and focused, especially when passing small functions.
Remember that lambdas can be assigned to delegates or expression trees depending on context.
Summary
Lambda expressions are short, unnamed functions written with => syntax.
They help write cleaner and shorter code for small functions.
You can use them anywhere a delegate or function is needed, like filtering or transforming data.