Lambdas

Create anonymous methods using a more concise syntax.

Overview

Lambdas are a simpler way to declare anonymous methods, though the syntax might look a bit tricky at first.

Let’s look at an example. We’ll rewrite the code from the previous lesson:

Press + to interact
using System;
namespace Lambdas
{
delegate int MathOperation(int operand1, int operand2);
class Program
{
static void Main(string[] args)
{
// Lambda expression
MathOperation mathOperation = (operand1, operand2) => operand1 + operand2;
// Lambda expression
mathOperation += (x, y) => x - y;
Console.WriteLine(mathOperation(2, 3));
}
}
}

Syntax and usage

Let’s disassemble the lambda expression to understand its individual parts: ...