1

I have a very simple use case:

class Program
{
    private static void Test()
    {
        {
            const bool thing = false;
        }

        bool thing = true;
    }

    static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

I'm getting this error when I compile this code:

main.cs(12,14): error CS0136: A local variable named 'thing' cannot be declared in this scope because it would give a different meaning to 'thing', which is already used in a 'child' scope to denote something else

Why does the second declaration of thing interfere with the first? I come from a heavy C++ background, so I was expecting this to be semantically the same: The two are separated by scope. In my mind, the const bool thing should not be available to the outer scope. What am I missing here?

Note that I did my best to google this, but unfortunately I don't know the correct terms to search for, so I've been unable to find an example of someone else trying this.

Note I'm using C# version 8 on .NET Framework 4.8.

void.pointer
  • 24,859
  • 31
  • 132
  • 243
  • 3
    The language design team made an explicit decision to forbid this, in an effort to help avoid bugs – canton7 Jun 18 '20 at 16:06
  • Adhoc meta question: Are people normally supposed to be marking questions as duplicate by linking to yet another duplicate? How far down the rabbit hole must I go? – void.pointer Jun 18 '20 at 16:12
  • That has a decent accepted answer in its own right, which IMO makes it a fine thing to link to. I've added *its* duplicate as a link here as well – canton7 Jun 18 '20 at 16:13

0 Answers0