Let’s go through lambda expressions in C# β€” a concise way to define anonymous functions.


πŸ“Œ 1. What is a Lambda Expression?

  • A lambda expression is an inline, anonymous function

  • Can be assigned to delegates or Func/Action types

  • Uses the => (goes to) operator

Basic Syntax

(parameters) => expression
  • If multiple statements, use curly braces {}

πŸ“Œ 2. Example with a Delegate

public delegate int MathOperation(int x, int y);
 
MathOperation add = (a, b) => a + b;
Console.WriteLine(add(5, 3)); // 8
  • (a, b) β†’ parameters

  • a + b β†’ expression returned

  • => separates parameters from body


πŸ“Œ 3. Lambda with Multiple Statements

MathOperation multiply = (a, b) =>
{
    int result = a * b;
    return result;
};
 
Console.WriteLine(multiply(4, 5)); // 20
  • Use curly braces and return for multiple statements

πŸ“Œ 4. Using Lambdas with Func and Action

  • Func<T1, T2, TResult> β†’ returns a value

  • Action<T1, T2> β†’ no return value

Func Example

Func<int, int, int> subtract = (x, y) => x - y;
Console.WriteLine(subtract(10, 4)); // 6

Action Example

Action<string> greet = name => Console.WriteLine("Hello " + name);
greet("Alice"); // Hello Alice

πŸ“Œ 5. Lambda Expressions with LINQ

  • Lambdas are heavily used in LINQ queries
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
 
foreach (var n in evenNumbers)
    Console.WriteLine(n); // 2, 4
  • n => n % 2 == 0 is the predicate lambda

πŸ“Œ 6. Advantages of Lambda Expressions

  1. Concise β†’ no need to define separate methods

  2. Readability β†’ especially with LINQ queries

  3. Type Inference β†’ compiler infers parameter types

  4. Functional Programming Style β†’ easy to chain operations


πŸ“Œ 7. Summary Table

FeatureDescription
Syntax(parameters) => expression
FuncDelegate that returns a value
ActionDelegate that does not return a value
Use CasesLINQ queries, callbacks, inline methods
Multi-line BodyUse { } and return

βœ… Tip:

  • Use lambda expressions for short inline methods

  • Combine with LINQ for powerful, readable data manipulation