Programming with Lambda Expressions in VB9, Page 2
What Are Closures?
A closure is another one of those things that keeps consultants (and authors) in business. A closure is basically a wrapper class that is emitted when you use local variables and return Lambda expressions from functions. Look at Listing 4.
Listing 4: Code that will emit a wrapper class called a "Closure" because you are returning a local variable and Lambda expression from a function.
Public Function ReturnClosure() Dim x As Integer Dim Lambda_Function = Function(y) x + y Return Lambda_Function End Function
In Listing 4, the local variable x is used in the Lambda expression referred to by Lambda_Function. The Lambda Function(y) x + y also exists only in the Function ReturnClosure. Both x and the Lamdba expression exist in local scope and would normally be cleaned up when the function exits and its stack is cleaned up. To support return x and the Lambda expression, the .NET framework emits a wrapper class—the closure—and the wrapper class has a field x and the Lambda expression to extend its life beyond the local function. The compiler handles this for you, but the result is a class that looks something like Listing 5.
Listing 5: The closure, or wrapper, that supports returning the reference to x and the Lambda expression.
Public Class Lambda_Function Public x As Integer Public Function Lambda_Function(y As Integer) As Integer Return y + x End Function End Class
Again, the compiler takes care of all this plumbing, but it's helpful to know what's going on.
Lambda expressions are very compressed, shortened-notation functions. They were invented to support more dynamic ways of programming, including putting behaviors in LINQ queries. Lambda expressions are nothing to fear and closures are just wrappers to facilitate passing locally defined expressions around your code.
The .NET framework is still emitting strongly typed code and Orca's features, such as Lambda expressions, are fully integrated elements of the upcoming version of .NET.
Hope you had fun at TechEd 2007.
About the Author
Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his new book UML DeMystified from McGraw-Hill/Osborne. Paul is a software architect for Tri-State Hospital Supply Corporation. You may contact him for technology questions at email@example.com.
If you are interested in joining or sponsoring a .NET Users Group, check out www.glugnet.org.
Copyright © 2007 by Paul T. Kimmel. All Rights Reserved.