Why is this working as expected:
list.ForEach(sub(x) x.Name = "New Name")
But this isn't:
list.ForEach(function(x) x.Name = "New Name")
Anyone else confused?
When you are using the Function
keyword
list.ForEach(Function(x) x.Name = "New Name")
you are creating a function that takes an argument named x
and returns a bool
(in this case).
So, in this case, =
is not the assignment operator, but the comparison operator, hence the Name
property is not changed.
(The compiler infers that the function returns a bool
due to the comparison operator)
It's equivalent to
list.ForEach(sub(x) Foobar(x))
...
Function Foobar(x as Foo) As Boolean
Return x.Name = "New Name" 'returns a boolean'
End Function
List(Of T).ForEach takes as an argument an Action (Sub) that doesn't return a value not a Func (Function) that does return a value.
In VB the = sign is ambiguous. It can either be used for comparison or assignment. As a result to disambiguate the statement, x.Name = "New Name"
the team used the indicator Sub or Function to identify if this is a comparison or assignment. In the case of Sub(x) x.Name = "New Name"
, you are performing an assignment, or set the value of x's Name parameter to "New Name". In the case of Function(x) x.Name = New "Name"
you are doing a comparison and returning if the Name parameter of x is the same as "New Name". As a result, you have to be careful when you use Sub and Function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With