Skip to content

C# is too restrictive about local variable scopes #2574

Discussion options

You must be logged in to vote

This is intentional (and has been since 1.0) as it's a common source of bugs where someone adds a variable and doesn't realize it's now shadowing something else. If you want to explicitly show that you want this, you can, by writing:

void Foo()
{
  {
    int x = 5;
    Console.WriteLine(x);
  }
  {
    int x = 6;
    Console.WriteLine(x);
  }
}

C# asks you to make your intent clear to prevent accidental bugs. This is similar to how case-fallthrough is not a thing for case-blocks with statements in them. Instead, you have to do an explicit goto to convey that you want hte fallthrough to happen intentionally.

Replies: 20 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by YairHalberstadt
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
10 participants
Converted from issue

This discussion was converted from issue #2574 on October 28, 2020 08:37.