C# 7, “out var” and changing variable scope, revisited

! Warning: this post hasn't been updated in over three years and so may contain out of date information.

Recently, I blogged about the planned changes to variable scope in C# 7, to enable more functionality around the new out var feature.Since writing that post, the leakage rules have changed, so I thought it time to revisit the topic.

Andrew Hanlon raised a Github issue, with regards to problems with allowing scope leakage in while loops and the lambda capture issue that affected foreach in early versions of C#. As a result of that, the language team changed the rules once more. First it was announced that variables wouldn’t leak out of while loops. Later, this was clarified to confirm that do while loops wouldn’t allow leakage either.

Now, scope leakage only occurs when out var (and is T, more on that next) if used with if expressions. Whilst not a complete “victory for common sense”, it is still good news.

Disappointingly, there has been no movement on fixing the is T “bug” that the scope leakage rules introduce. The team seem determined to stick to their “consistent, but makes no sense” stance with regard to allowing the variable to leak, even though it can’t be used as it may not be assigned:

On Github at least, opinion of this feature remains firmly in the “makes no sense” camp. As this will trip up many developers, and “fixing” it won’t be a breaking change, I still predict that the team will back down at some stage after releasing v7. The sooner the better…

Posted in C#