Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.ForEach in vb.net - perplexing me

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...

like image 817
Graham Whitehouse Avatar asked Jan 17 '12 16:01

Graham Whitehouse


1 Answers

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.

like image 102
Meta-Knight Avatar answered Nov 10 '22 03:11

Meta-Knight