0

Today I discovered a, presumably, "feature" of :

error CS0136: A local variable named foo cannot be declared in this scope because it would give a different meaning to foo, which is already used in a child scope to denote something else

Which can simply be reproduced by trying to compile this snippet:

if (false) {
    int foo = 42;
}
int foo = 1337;

Why can't I define foo in the parent scope? The foo from the child scope is not visible in the parent scope, nor would it be still allocated, it's therefore absolutely legal in any proper language. What did I miss? What is the reasoning behind this?

Leandros
  • 16,805
  • 9
  • 69
  • 108
  • It's obviously rather a design choice than a feature: http://stackoverflow.com/a/2049377/2695832 – Onkel Toob Aug 19 '16 at 08:25
  • Sweet! Thanks a lot. For some reason I couldn't find anything related to that. Yes, it's a duplicate. – Leandros Aug 19 '16 at 08:31
  • possible duplicate: http://stackoverflow.com/questions/2049330/c-sharp-variable-scoping http://stackoverflow.com/questions/6156449/why-cant-a-duplicate-variable-name-be-declared-in-a-nested-local-scope http://stackoverflow.com/questions/4649947/why-doesnt-c-sharp-allow-me-to-use-the-same-variable-name-in-different-scopes – Konstantin Ershov Aug 19 '16 at 08:31
  • @OnkelToob I really feel like C# was designed for a toddler ... – Leandros Aug 19 '16 at 08:31

0 Answers0