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

Lambda with captures (closures) in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a lambda expression in C#?
A lambda expression is a short way to write an anonymous function using the syntax (parameters) => expression or block. It can be used to create inline functions.
Click to reveal answer
intermediate
What does it mean when a lambda "captures" a variable?
Capturing means the lambda uses a variable from its surrounding scope. The lambda keeps a reference to that variable, so it can use or change it even after the original scope ends.
Click to reveal answer
intermediate
Explain what a closure is in C#.
A closure is a lambda or anonymous function that captures variables from its surrounding scope. It 'closes over' those variables, keeping them alive and accessible inside the lambda.
Click to reveal answer
intermediate
Consider this code snippet:<br>
int x = 5;<br>Func<int> f = () => x + 1;<br>x = 10;<br>Console.WriteLine(f());
<br>What will be printed and why?
It will print 11. The lambda captures the variable x by reference, not by value. So when x changes to 10, the lambda uses the updated value.
Click to reveal answer
beginner
Why are closures useful in programming?
Closures let you keep state inside functions without using classes or global variables. They help write cleaner, more flexible code by bundling data with behavior.
Click to reveal answer
What does a lambda capture in C#?
ANothing, lambdas cannot capture variables
BOnly constants
COnly parameters passed to it
DVariables from its surrounding scope
If a lambda captures a variable, what happens when the variable changes after the lambda is created?
AThe lambda sees the updated value
BThe lambda keeps the original value forever
CThe lambda throws an error
DThe lambda copies the value once and ignores changes
What is a closure in C#?
AA static method
BA lambda that captures variables from its environment
CA method with no parameters
DA class with private fields
Which of these is a correct lambda syntax in C#?
A() => 42
Blambda() { return 42; }
Cfunction() => 42
Ddef lambda(): return 42
Why might you use a closure instead of a class?
ABecause closures are faster than classes
BBecause classes cannot hold state
CTo keep state in a small, simple function without extra code
DBecause closures do not use memory
Describe how a lambda captures variables and what effect this has on variable values inside the lambda.
Think about what happens if the variable changes after the lambda is created.
You got /3 concepts.
    Explain what a closure is and why it is useful in C# programming.
    Closures bundle data and behavior together.
    You got /4 concepts.