Comparison with lambdas
Context: Lambdas are more concise and expressive than anonymous methods. They are the preferred way to write inline functions in modern C#.
Syntax comparison
Section titled “Syntax comparison”// Anonymous methodFunc<int, int> anon = delegate(int x) { return x * x; };
// Lambda expressionFunc<int, int> lambda = x => x * x;Features exclusive to lambdas
Section titled “Features exclusive to lambdas”- Expression tree conversion (
Expression<Func<T>>) - Natural type inference
- Shorter syntax for single‑expression bodies
Expression<Func<int, int>> expr = x => x * x; // works with lambda onlyWhen to use anonymous methods
Section titled “When to use anonymous methods”- You need to omit parameters (delegate with no parameters but still accept any)
- You are targeting C# 2.0
Action act = delegate { Console.WriteLine("No params"); };// Lambda would require () => ...Real-world usage example
Section titled “Real-world usage example”Modern .NET code: Always prefer lambdas. Anonymous methods are only used for backward compatibility.
Example: Microsoft documentation recommends lambdas for new development.