C# Anonymous Methods and Lambda Expressions


Anonymous Methods and Lambda Expressions in C# are powerful features that allow you to define inline functions without explicitly declaring a separate method. They are particularly useful in scenarios such as event handling, LINQ queries, and callback functions, where you need a temporary function that doesn't require a formal declaration.

Anonymous Methods

An anonymous method is a way to define a method without a name. It can be assigned to a delegate and can take parameters and return a value. Anonymous methods were introduced in C# 2.0 and provide a way to write inline code that can be executed later.

Key Characteristics of Anonymous Methods

  1. Inline Definition: Anonymous methods are defined inline and do not require a separate method declaration.
  2. Delegate Invocation: They can be assigned to delegates, allowing you to pass them around as parameters.
  3. Variable Scope: Anonymous methods can capture variables from their enclosing scope, which can lead to closures.

Example of Anonymous Methods

using System; public class Program { public delegate void Notify(string message); public static void Main() { // Assign an anonymous method to the delegate Notify notifyDelegate = delegate (string message) { Console.WriteLine($"Notification: {message}"); }; // Invoke the anonymous method notifyDelegate("This is an anonymous method example!"); } }

Lambda Expressions

Lambda expressions are a more concise way to write anonymous methods, introduced in C# 3.0. They provide a syntactical shorthand for creating anonymous functions and can be used anywhere a delegate type is expected.

Key Characteristics of Lambda Expressions

  1. Conciseness: Lambda expressions provide a more concise syntax compared to anonymous methods, reducing boilerplate code.
  2. Expression Trees: They can be used to create expression trees, which are useful in scenarios such as LINQ queries.
  3. Type Inference: The type of the input parameters can be inferred, allowing for cleaner code.

Syntax of Lambda Expressions

The basic syntax of a lambda expression is:

(parameters) => expression

Or for multiple statements:

(parameters) => { statements }

Example of Lambda Expressions

using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { // Using a lambda expression to define a method for the delegate Func<string, string> notify = message => $"Notification: {message}"; // Invoke the lambda expression Console.WriteLine(notify("This is a lambda expression example!")); // Using lambda expressions with LINQ List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; var evenNumbers = numbers.Where(n => n % 2 == 0).ToList(); // Get even numbers Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers)); } }

Comparison of Anonymous Methods and Lambda Expressions

FeatureAnonymous MethodsLambda Expressions
SyntaxUses the delegate keywordUses the => syntax
VerbosityMore verboseMore concise
Return TypeCan be inferredCan be inferred
Scope of VariablesCan capture variables from enclosing scopeCan capture variables from enclosing scope
Expression TreesNot applicableCan create expression trees

Summary

  • Anonymous Methods provide a way to define inline methods without a name, making them useful for event handling and delegate invocation.
  • Lambda Expressions offer a more concise syntax for creating anonymous methods, enabling cleaner and more readable code.
  • Both features facilitate functional programming patterns in C#, allowing for more expressive and flexible code when working with delegates, LINQ queries, and asynchronous programming.

These tools are particularly valuable in modern C# programming, especially in scenarios involving asynchronous operations, event handling, and functional programming paradigms.