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

Comments

No Comments Yet.
Be the first to tell us what you think.