VB Quark #0 : lambda expressions and statements

Posted Fri, Sep 23 2011 12:43 by bill

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
End
 
Class

 

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)
     
'code here
   End 
Sub

 

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 :

      customers.ForEach(Function(cust)
                          
Return cust.Approved = True
                        End Function)

 

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.

Filed under: , , , ,

Comments

# re: VB Quark #0 : lambda expressions and statements

Wednesday, December 14, 2011 8:08 AM by Torsten Tiedt

Hi Bill,

thanks four your post. In fact, another blog:

blogs.lessthandot.com/.../vb-net-addhandler-and-lambdas

treats the same problem, but your's is clearer. In fact, they needed some replies to get to your point ;)

And by the way: thanks for your snippetmanager. I use it a lot!

Keep care,

Torsten