Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it bad to use an iteration variable in a lambda expression

I was just writing some quick code and noticed this complier error

Using the iteration variable in a lambda expression may have unexpected results.
Instead, create a local variable within the loop and assign it the value of the iteration variable.

I know what it means and I can easily fix it, not a big deal.
But I was wondering why it is a bad idea to use a iteration variable in a lambda?
What problems can I cause later on?

like image 965
Nathan W Avatar asked Oct 22 '08 22:10

Nathan W


People also ask

Can we use instance variable in lambda expression?

A Lambda expression can also access an instance variable. Java Developer can change the value of the instance variable even after its defined and the value will be changed inside the lambda as well.

Can we change the lambda expression variable data?

Yes, you can modify local variables from inside lambdas (in the way shown by the other answers), but you should not do it.

What is the point of lambdas?

Lambda functions are intended as a shorthand for defining functions that can come in handy to write concise code without wasting multiple lines defining a function. They are also known as anonymous functions, since they do not have a name unless assigned one.


1 Answers

Consider this code:

List<Action> actions = new List<Action>();  for (int i = 0; i < 10; i++) {     actions.Add(() => Console.WriteLine(i)); }  foreach (Action action in actions) {     action(); } 

What would you expect this to print? The obvious answer is 0...9 - but actually it prints 10, ten times. It's because there's just one variable which is captured by all the delegates. It's this kind of behaviour which is unexpected.

EDIT: I've just seen that you're talking about VB.NET rather than C#. I believe VB.NET has even more complicated rules, due to the way variables maintain their values across iterations. This post by Jared Parsons gives some information about the kind of difficulties involved - although it's back from 2007, so the actual behaviour may have changed since then.

like image 59
Jon Skeet Avatar answered Oct 09 '22 01:10

Jon Skeet