C# Lambda expressions and anonymous functions

Updated: 28 January 2023

A lambda expression is used to create an anonymous function. The lambda declaration operator => separates the lambda’s parameter list from its body.

Expression lambda. Returns the result of the expression

// (input-parameters) => expression

Statement lambda

// (input-parameters) => { <statement block> }

Action<string> greet = name =>
{
    string greeting = $"Hello {name}";
    Console.WriteLine(greeting);
};

// greet("World");

Input parameters

// none
Action line = () => Console.WriteLine();

// one
Func cube = x => x * x * x;
Func cube = (x) => x * x * x;

// two or more
Func testForEquality = (x, y) => x == y;

// with types
Func isTooLong = (int x, string s) => s.Length > x;

Discards specify input parameters which are not used in the expression

Func<int, int, int> constant = (_, _) => 42;

Leave a comment