0
0
C Sharp (C#)programming~3 mins

Why Lambda with captures (closures) in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could remember things for you, so you never mix up important details again?

The Scenario

Imagine you want to create a list of buttons in a program, and each button should remember its own number to show when clicked. Doing this manually means writing separate code for each button to remember its number.

The Problem

Writing separate code for each button is slow and boring. It's easy to make mistakes, like mixing up numbers or forgetting to update one button. If you want to change the behavior, you have to fix many places, which wastes time and causes bugs.

The Solution

Using lambda with captures lets you write one small piece of code that remembers the number automatically. This way, each button keeps its own number without extra work. It's like giving each button a little memory, so your code stays short, clear, and easy to change.

Before vs After
Before
for (int i = 0; i < 3; i++) {
  int num = i;
  buttons[i].Click += delegate { Console.WriteLine(num); };
}
After
for (int i = 0; i < 3; i++) {
  int num = i;
  buttons[i].Click += () => Console.WriteLine(num);
}
What It Enables

It enables writing simple, reusable code that remembers important values automatically, making programs easier to build and maintain.

Real Life Example

Think of a photo gallery app where each thumbnail remembers which photo it shows. Using lambda with captures, each thumbnail button can show the right photo without extra code for each one.

Key Takeaways

Manual code for remembering values is repetitive and error-prone.

Lambdas with captures let code remember values automatically.

This makes programs simpler, cleaner, and easier to update.