C#:C# Lambda Expressions and Delegates (Action, Func)
C#•Lambdas & Delegates

C# Lambda Expressions and Delegates (Action, Func)

Learn delegate types in C#: Action<T> for void returns and Func<T, TResult> for value returns.

Syntax

Func<int, int, int> add = (a, b) => a + b; Action<string> print = s => Console.WriteLine(s);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
Func<T, TResult>DelegateEncapsulates a method that returns a value.
Action<T>DelegateEncapsulates a method that returns void.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C# locally:

using System;

public class Program {
    public static void Main() {
        // 1. Func delegate returning double
        Func<double, double, double> computeArea = (width, height) => width * height;
        Console.WriteLine($"Rectangle Area: {computeArea(5.5, 4.0)}");

        // 2. Action delegate for side-effects
        Action<string> logMessage = msg => Console.WriteLine($"[LOG {DateTime.UtcNow:HH:mm:ss}] {msg}");
        logMessage("Application initialized.");
        logMessage("Worker thread running.");
    }
}
Expected Output:
Rectangle Area: 22
[LOG [time]] Application initialized.
[LOG [time]] Worker thread running.

How It Works: Step-by-Step

  • Line 6: Func takes two double parameters and returns double.
  • Line 10: Action takes string parameter and returns void.

Key Concepts

  • Func always has its return type as the last generic parameter.
  • Action can accept up to 16 parameters and always returns void.

Common Mistake: Confusing Func with Action

Action does not return a value. If your lambda returns a value, use Func.

❌ Incorrect
Action<int, int> add = (a, b) => a + b; // Compile Error: cannot return a value
✅ Correct
Func<int, int, int> add = (a, b) => a + b;

Related C# Tutorials & Compiler

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler