Search⌘ K
AI Features

Lambdas

Explore how to use lambda expressions in C# as a concise way to represent anonymous methods within delegates and events. Understand their syntax, including parameters, return values, and passing lambdas as method arguments. Gain clarity on why lambdas are preferred over anonymous methods for modern C# programming.

Lambda expressions (or simply “lambdas”) are a concise way to represent anonymous methods. They allow us to write code that is shorter and often more readable than using the delegate keyword.

Creating a delegate with a lambda

Let’s rewrite the example from the previous lesson using a lambda expression.

C# 14.0
// Lambda expression defined with the => operator
MathOperation mathOperation = (operand1, operand2) => operand1 + operand2;
// We can add another lambda to the invocation list
mathOperation += (x, y) => x - y;
Console.WriteLine(mathOperation(2, 3));
delegate int MathOperation(int operand1, int operand2);
  • Line 2: We define a lambda expression (operand1, operand2) => operand1 + operand2. The compiler infers that operand1 and operand2 are integers based on the MathOperation delegate definition. ...