Tuesday, October 22, 2013

VB .NET - Lambdas

I have recently discovered that lambdas are amazing things. They take a little bit of getting used to, but once mastered, correct use of them will save programmer time and increase program efficiency. A lambda, essentially, is a function or subroutine written in one line that can be passed as an argument, usually in a LINQ method. When a method expects an argument of type Func or Sub (like IEnumerable.ForEach), it's time for a lambda. Start a lambda by writing Function or Sub and an argument in parentheses without type - the object that's going to be put in as the input of the lambda method. Then, simply write the return value. The simplest lambda is the identity lambda: Function(n) n. It takes in object n and returns it. For a Sub, you obviously won't have a return value, so just write what action it performs. Sub(n) MsgBox(n.ToString) accepts object n and writes its string representation in a message box. If you are using more complicated methods, use an AddressOf pointer to indicate that you want to pass the objects through a declared method.

No comments:

Post a Comment