0
0
CsharpHow-ToBeginner · 3 min read

How to Use Lambda Expressions in C# - Simple Guide

In C#, a lambda expression is a concise way to write anonymous functions using the syntax (parameters) => expression. You use lambdas to create inline functions for delegates or LINQ queries easily.
📐

Syntax

A lambda expression uses the => operator to separate parameters and the function body.

  • Parameters: Input values, can be typed or inferred.
  • => : Lambda operator, means 'goes to'.
  • Expression or block: The code executed, can be a single expression or multiple statements in braces.
csharp
(parameters) => expression

// Example:
int x => x * x;
💻

Example

This example shows how to use a lambda to square numbers in a list and print the results.

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

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

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

        foreach (var square in squares)
        {
            Console.WriteLine(square);
        }
    }
}
Output
1 4 9 16 25
⚠️

Common Pitfalls

Common mistakes when using lambdas include:

  • Forgetting parentheses for multiple parameters, e.g., x, y => x + y is invalid; use (x, y) => x + y.
  • Using statement blocks without braces when needed.
  • Confusing lambda expressions with method groups.
csharp
/* Wrong: Missing parentheses for multiple parameters */
// var add = x, y => x + y; // Error

/* Correct: Use parentheses */
var add = (x, y) => x + y;
📊

Quick Reference

ConceptDescriptionExample
Single parameterNo parentheses neededx => x * 2
Multiple parametersUse parentheses(x, y) => x + y
No parametersEmpty parentheses() => 42
Expression bodySingle expression returns valuex => x * x
Statement bodyUse braces and return(x) => { return x + 1; }

Key Takeaways

Use => to create concise anonymous functions called lambda expressions.
Parentheses are required for zero or multiple parameters but optional for one parameter.
Lambdas can be used anywhere a delegate or expression tree is expected, like LINQ.
Watch out for syntax errors with parameters and statement blocks.
Lambdas help write cleaner, shorter code for inline functions.