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:
| Parameter | Type | Description |
|---|---|---|
| Func<T, TResult> | Delegate | Encapsulates a method that returns a value. |
| Action<T> | Delegate | Encapsulates a method that returns void. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C# Named and Optional Parameters in Method Definitions
Define flexible C# methods using optional parameters with defaults and named arguments (name: value) for order independence and clarity.
C# Classes, Records, and Properties (get; set;)
Design objects using classes, auto-properties ({ get; set; }), and modern C# records.
C# List<T> and LINQ Queries: Where, Select, and Aggregate
Master dynamic List<T> collections and powerful LINQ queries (Where, Select, Sum).
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.