What if your code could remember things for you, so you never mix up important details again?
Why Lambda with captures (closures) in C Sharp (C#)? - Purpose & Use Cases
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.
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.
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.
for (int i = 0; i < 3; i++) { int num = i; buttons[i].Click += delegate { Console.WriteLine(num); }; }
for (int i = 0; i < 3; i++) { int num = i; buttons[i].Click += () => Console.WriteLine(num); }
It enables writing simple, reusable code that remembers important values automatically, making programs easier to build and maintain.
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.
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.