Understanding Anonymous Methods and Lambda Expressions in C#

Anonymous Methods

Typically, methods are members of structures or classes that can be invoked directly. However, there are scenarios where a method is needed only once—specifically to instantiate a delegate. In such cases, creating a separate named method would be unnecessary overhead. Anonymous methods provide an inline declaration within the delegate instantiation.

class Program
{
    delegate int ComputeDelegate(int input);
    
    static void Main()
    {
        ComputeDelegate processor = delegate(int num) { return num * 2; };
        Console.WriteLine($"Result: {processor(10)}");
        Console.WriteLine($"Result: {processor(25)}");
    }
}

Where Anonymous Methods Apply

Anonymous methods work in several contexts:

  • Initializing delegate variables during declaration
  • Combining delegates on the right side of assignment statements
  • Ataching event handlers when assigning to delegates

Syntax Structure

An anonymous method consists of:

  • The delegate keyword
  • An optional parameter list (omittable if the body uses no parameters)
  • A statement block containing the method's implementation
delegate(parameters)
{
    // implementation
}

Return Values

Anonymous methods don't explicitly declare return types. Instead, the implementation must return a value matching the delegate's return type. For void delegates, no return statement is permitted.

delegate string FormatterDelegate(string input);
FormatterDelegate formatter = delegate(string text)
{
    return text.ToUpper();
};
delegate void ActionDelegate(string message);
ActionDelegate logger = delegate(string msg)
{
    Console.WriteLine(msg);
};

Parameters

The anonymous method's parameter list must match the delegate's in three aspects: count, types and positions, and modifiers. Two exceptions allow simplification:

  • When the method takes no parameters, the parameter list can be empty or omitted entirely
  • This applies only if no out parameters exist in the delegate signature
delegate void SimpleDelegate();
SimpleDelegate greet = delegate
{
    Console.WriteLine("Hello, World!");
};

The params Keyword

When a delegate declares a params parameter, the anonymous method's parameter list should omit the params keyword but include the array parameter itself.

delegate int SumDelegate(int first, params int[] rest);
SumDelegate sum = delegate(int start, int[] values)
{
    int total = start;
    foreach (int n in values)
        total += n;
    return total;
};

Variable and Parameter Scope

Captured Variables

Unlike regular methods, anonymous methods can access local variables from their enclosing scope. These are called captured variables or external variables. The technique of referencing outer scope variables within an anonymous method is known as variable capture.

Lifetime Extension of Captured Variables

Captured variables remain valid even after they leave their original scope, as long as the delegate referencing them continues to exist. This lifetime extension occurs because the anonymous method keeps a reference to the captured variables within the delegate's closure.

Lambda Expressions

Lambda expressions provide a more concise syntax for creating anonymous methods. The delegate keyword becomes unnecessary when using lambda syntax.

Converting Anonymous Methods to Lambda Expressions

To convert an anonymous method to a lambda expression:

  1. Remove the delegate keyword
  2. Insert the lambda operator (=>) between the parameter list and the method body
// Anonymous method
MyDelegate handler = delegate(int n) { return n + 5; };

// Equivalent lambda expression
MyDelegate handler = (int n) => { return n + 5; };

Progressive Simplification

Lambda expressions support several levels of syntactic sugar:

  • Type inference: Since the compiler can infer parameter types from the delegate signature, explicit type declarations are optional. Explicit types are called explicitly typed; omitted types are implicitly typed.
  • Parentheses: When there's a single implicitly typed parameter, parentheses are optional.
  • Expression bodies: If the statement block contains only a return statement, the entire block can be replaced with the expression following return.
MyDelegate original = delegate(int x) { return x + 1; };
MyDelegate v1 = (int x) => { return x + 1; };
MyDelegate v2 = (x) => { return x + 1; };
MyDelegate v3 = x => { return x + 1; };
MyDelegate v4 = x => x + 1;

Lambda Expression Parameter Rules

Key considerations for lambda parameter lists:

  • Parameter count, type, and position must align with the delegate signature
  • Implicit typing is allowed unless the delegate uses ref or out parameters, in which case explicit typing is required
  • Single implicit parameters don't require parentheses; all other cases must include them
  • No parameters requires an empty pair of parentheses

Tags: C# Anonymous Methods Lambda Expressions Delegates Syntax

Posted on Fri, 08 May 2026 12:54:05 +0000 by youscript