Lambda vs Anonymous Method in C#: Key Differences and Usage
lambda expressions are a concise way to write inline functions using the => syntax, while anonymous methods use the delegate keyword to define inline code blocks. Lambdas are more modern, flexible, and preferred for readability and expression-bodied syntax compared to anonymous methods.Quick Comparison
Here is a quick side-by-side comparison of lambda expressions and anonymous methods in C#.
| Factor | Lambda Expression | Anonymous Method |
|---|---|---|
| Syntax | Uses => operator (e.g., (x) => x * 2) | Uses delegate keyword (e.g., delegate(int x) { return x * 2; }) |
| Introduced in | C# 3.0 | C# 2.0 |
| Conciseness | More concise and readable | More verbose |
| Type inference | Supports type inference for parameters | Requires explicit parameter types or none |
| Use cases | Preferred for LINQ and functional style | Used before lambdas existed or for complex inline code |
| Access to outer variables | Can capture outer variables (closures) | Can also capture outer variables |
Key Differences
Lambda expressions provide a shorter and clearer syntax for writing inline functions using the => operator. They support type inference, so you often don't need to specify parameter types explicitly, making the code cleaner. Lambdas are heavily used in LINQ queries and functional programming styles in C#.
Anonymous methods use the delegate keyword and require either explicit parameter types or no parameters at all. They were introduced earlier than lambdas and are more verbose. Anonymous methods allow inline code blocks but lack the concise syntax and flexibility of lambdas.
Both can capture variables from the surrounding scope (closures), but lambdas are generally preferred today for their readability and expressiveness. Lambdas can also be converted to expression trees, enabling advanced scenarios like query translation, which anonymous methods cannot.
Code Comparison
Here is how you write a simple function that doubles a number using a lambda expression.
Func<int, int> doubleLambda = x => x * 2; Console.WriteLine(doubleLambda(5));
Anonymous Method Equivalent
The equivalent code using an anonymous method looks like this.
Func<int, int> doubleAnonymous = delegate(int x) { return x * 2; }; Console.WriteLine(doubleAnonymous(5));
When to Use Which
Choose lambda expressions when you want concise, readable code especially for simple operations, LINQ queries, or when you want to leverage type inference and expression trees. Lambdas are the modern standard and preferred in most cases.
Use anonymous methods if you are maintaining legacy code or need to write more complex inline code blocks that might not fit well in a single expression. However, these cases are rare since lambdas can handle most scenarios.