Programming with Lambda Expressions in VB9
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
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.
Page 2 of 2