VB Quark #0 : lambda expressions and statements
Fri, Sep 23 2011 12:43
This VB Quark is the one that started the conversation some weeks back. It’s number 0, both because these days things are typically 0 based in .NET, and also you could say it is ground zero. It’s about a quirk quark to do with lambda functions versus lambda subs.
Let’s say you have a Customer class that has an Approved property : Class Customer
Public Property Approved As Boolean
Now if you were to write the following code on a list of Customer, what would you expect to happen ?
customers.ForEach(Function(cust) cust.Approved = True)
If you said nothing, you’d be pretty close to the answer.
The quirk quark here is two fold. First of, ForEach expects an Action(Of T) to be passed to it. Action(Of T) in this case has the form of:
Sub DoAction(cust As Customer)
But note we passed in a Function. Function’s have return types. In this case the return type is a Boolean implied from the expression cust .Approved =True . That is the = operator is an equality operation in this case, not an assignment operator. The original expression is seen by the compiler as the equivalent of :
Return cust.Approved = True
If you actually want to set the IsApproved values in the ForEach you can simply use a Sub instead of a Function:
customers.ForEach(Sub(cust) cust.Approved = True)
So the quarks to remember here are the = operator in VB can be either equality test or assignment depending on the context; and not all lambdas are lambda expressions (aka Functions), some can be lambda statements (aka Sub)
I’ve seen this quark trip up a couple of really smart people, usually when they are translating code from C# to VB. Apparently some translation tools also make the same mistake.