List.ForEach in vb.net - perplexing me

Graham Whitehouse picture Graham Whitehouse · Jan 17, 2012 · Viewed 31.9k times · Source

Consider the following code example:

    TempList.ForEach(Function(obj)
        obj.Deleted = True
    End Function)

And this one:

    TempList.ForEach(Function(obj) obj.Deleted = True)

I would expect the results to be the same, however the second code example does NOT change the objects in the list TempList.

This post is more to understand why...? Or at least get some help understanding why...

Answer

Meta-Knight picture Meta-Knight · Jan 17, 2012

It's because you used Function instead of Sub. Since a Function returns a value, the compiler considers that the equals sign (=) is used as a comparison, not an assignment. If you change Function to Sub, the compiler would correctly consider the equals sign as an assignment:

TempList.ForEach(Sub(obj) obj.Deleted = True)

If you had a multiline lambda; you wouldn't have had this problem:

TempList.ForEach(Function(obj)
                     obj.Deleted = True
                     Return True
                 End Function)

Obviously, for the ForEach method it makes no sense to use a Function because the return value wouldn't be used, so you should use a Sub.