Lambda functions/subs in VB.NET

Another programmer was asking me why you sometimes need “End Sub” on a Lambda Sub and sometimes you don’t. This was my reply…

There are 2 types of Lambda methods – inline and multi line. Inline is all on one line, so you can do…

Sub (x) DoSomethingWith(x)

nb. this is the same as

Sub (x) _
DoSomethingWith(x)

because VB.NET considers that multiple lines with _ at the end are all one. However, without the _ it is multiline…

Sub (x)
DoSomethingWith(x)
YouCanAlsoDoSomethingElseWith(x)
End Sub

That’s when you need End Sub – even if it is only one line in the body, you need to end it if you aren’t doing the body on the same line as the declaration.

nb. Functions work the same way, although there is one other difference with functions. Multiline functions work the same way as usual in terms of how you return from them, but inline you don’t use the Return keyword, so you would just do eg.

Function (x) x*2

In all of the above examples, you would want to provide types on the parameters (eg. x As Decimal). For inline functions, you can usually let the compiler work out the return type, but for multiline you should usually explicitly declare the return type (eg. Function(x As Decimal) As Decimal)

Leave a Reply