out varfeature.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:
object s = "";
if (s is int i)
Console.WriteLine(i); // i is in scope, but can't be used as it's not definitely 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…