What is variable capturing good for and how does it work?
Experience Level: Senior
Tags: .NETC#
Answer
Answer
C# gives us an ability to use closures. This is a powerful tool that allows anonymous methods and lambda-functions to capture unbound variables in their lexical scope. This way you can use outer variable from within the anonymous method even if the variable would normally be not available after you would get out of its original scope.
Good to know
- A reference to the outer variable is said to be captured when the delegate is created. Unlike local variables, the lifetime of a captured variable extends until the delegates that reference the anonymous methods are eligible for garbage collection.
- Closures close over variables, not over values. Every single access of captured variable in your program is accessing the same variable, there are never any copies made of it.
Links
Related C# job interview questions
What is JIT?
.NETASP.NET MVCASP.NET WebAPIASP.NET WebFormsC# SeniorWrite a code that takes an integer number and outputs its digits to the console.
.NETC#Code challenge MediorWhat will be the output of the following code that is using delegates?
.NETC#Code challenge SeniorCould you describe what generic type inference is and what will be the output of this program?
.NETC#Code challenge SeniorWhat is the difference between IEnumerable and IQueryable?
.NETC#Entity FrameworkLINQPerformance Senior