VB.NET Lambda capturing variables incorrectly

Why does a LINQ lambda inside UiPath sometimes capture an older variable value, and how do an i correct closure behavior?

Actually vb.net captures vaiables by reference, if any changes in variablethen lambda sees the new value not the originial

Dim v=outerVar
dt.AsEnumerable.Where(Function(r)(“col”)=v)

1 Like

@manish.pal Thank you very much !!

1 Like

LINQ lambda uses closure — meaning it remembers the variable reference, not the value at that moment.
So if the variable changes in a loop, the lambda may still point to the latest value, not the value from when the lambda was created.
This is why it sometimes picks an older or unexpected value.

Take for eg :
For Each i In {1,2,3}
query = list.Where(Function(x) x = i) 'captures reference to i
Next

All lambdas may end up using i = 3.
To solve this issue…

  1. Create a local copy inside the loop
    For Each i In {1,2,3}
    Dim current = i
    query = list.Where(Function(x) x = current)
    Next
    Now each lambda uses the correct value.

  2. Avoid using loop variables directly,Always assign to a temp variable first.

1 Like

why do linq filters inside for each produce incorrect result due to shared variable capture

All lambdas capture variables by reference, not by value and Each iteration overwrites the captured value.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.