Search⌘ K
AI Features

Lambdas

Explore how lambdas simplify declaring anonymous methods in C#. Learn the syntax of lambda expressions, including parameter handling, implicit typing, and usage as method parameters. Understand how lambdas integrate with delegates and events to write concise and functional code.

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:

C#
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: ...