Rohit Sharma
Rohit Sharma

Reputation: 6500

Does .net 5 compiler give warning for the loop-variable-closure issue?

I am currently working on a big project which uses .net 4 and in a few months we'd soon be moving to .net 5. I am wondering if .net 5 compiler gives warning to the loop-variable-closure issue? Other than resharper does fxcop/.net-5-compiler give warning to this?

The reason i am asking this is because i am afraid there will be a breaking change if we move our code base to .net 5, so wondering if there is a way (compiler, fxcop etc) to tell in advance that this might be an issue. I do not have resharper thus i ruled it out (better have support in the base tools)

Upvotes: 0

Views: 142

Answers (3)

i3arnon
i3arnon

Reputation: 116616

It seems you are confusing C# versions and .Net versions. The latest .Net version is 4.5 and the latest C# one is 5.0.

The breaking change fix only exists in C# version 5.0 and it only affects the foreach loop. As Console explained you would only need to worry about it if you were relying on that bug being there, which isn't likely. You can however safely use the latest .Net with an old C# version (i.e. 4.0).

If you do end up using C# version 5.0 you won't get a warning, because there's nothing to warn about anymore. The bug was fixed, even though it was a small breaking change.

Upvotes: 3

quadroid
quadroid

Reputation: 8950

The only thing where this does actually break production Code is if you rely on the fact that the loop variable is outside the loop. This should actually not happen as it is not intuitive at all.

        foreach (Button button in buttons)
            button.Click += (e, a) => Debug.WriteLine(button.Name);

This code will in C# 4 print the name of the last elemnt on every button, while in C# 5 it does print the right name on every button (which is actually what i would expect anyway)

So if you never did rely on that strange behavior of C# 4 there is no breaking change in your production code (regarding this change ofc)

To answer your question the compiler does not generate a warning (esp not the C# 5.0 Compiler as there is no issue anymore). And i don't think that fxcop provides a warning for this either.

Upvotes: 0

Ian
Ian

Reputation: 34519

This isn't an issue in the later compilers, Microsoft have addressed it and the code will run as you initially expect it to, without understanding the nuances.

From the answer https://stackoverflow.com/a/8899347/21061 Eric Lippert states

I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

So, you no longer need to worry.

Upvotes: 1

Related Questions