Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A statement lambda is a lambda expression in C# where the execution body is enclosed in a statement block { } containing one or more statements. Unlike expression lambdas, which evaluate and implicitly return a single expression, statement lambdas permit complex control flow, local variable declarations, and require an explicit return statement if the delegate signature expects a non-void return type.

Syntax

(input_parameters) => { sequence_of_statements; }

Technical Characteristics

  • Delegate Resolution: A statement lambda must be convertible to a compatible delegate type, typically from the Action family (for void returns) or the Func family (for value returns).
  • Return Semantics: If the target delegate type has a non-void return type, the statement block must contain an explicit return statement on all reachable code paths.
  • Expression Tree Incompatibility: Unlike expression lambdas, statement lambdas cannot be converted into expression trees (System.Linq.Expressions.Expression<TDelegate>). The C# compiler can only emit them as executable Intermediate Language (IL) bound to a delegate instance.
  • Lexical Scoping and Closures: The statement block defines a local scope. It can capture variables from the enclosing method (forming a closure), but variables declared within the { } block are strictly local to the lambda’s invocation.
  • Asynchronous Execution: Statement lambdas can be modified with the async keyword, allowing the use of await within the statement block. This resolves to an Action (if returning void), Func<Task>, or Func<Task<T>>.

Syntax Visualization

Void-returning Statement Lambda (Action)
Action<string> processString = (input) => 
{
    string normalized = input.Trim().ToLower();
    Console.WriteLine(normalized);
};
Value-returning Statement Lambda (Func)
Func<int, int, int> computeWithBranching = (x, y) => 
{
    int sum = x + y;
    if (sum < 0) 
    {
        return 0; // Explicit return required
    }
    return sum;   // Explicit return required
};
Asynchronous Statement Lambda
Func<string, Task<int>> fetchAndMeasureAsync = async (url) => 
{
    using var client = new HttpClient();
    string result = await client.GetStringAsync(url);
    return result.Length;
};
Parameter Discards in Statement Lambdas
// Using discards (_) for unused parameters in the delegate signature
Func<int, int, string> ignoreParameters = (_, _) => 
{
    string defaultState = "Unchanged";
    return defaultState;
};
Master C# with Deep Grasping Methodology!Learn More