Scope variable inside if

Possible duplicate:
C # with variable scale

I thought I could declare two variables with the same name if they are in different scopes:

namespace IfScope
{
    class Demo
    {
        public static void Main()
        {
            bool a = true;

            if ( a )
            {
                int i = 1;
            }
            string i  = "s";
        }
    }
}

      

The compiler says something else:

$ csc Var.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.

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

      

This would mean that i

, declared inside the if, is visible from the outside (this is what I figured out)

But if I try to use it, I get this.

$ cat Var.cs
namespace IfScope
{
    class Demo
    {
        public static void Main()
        {
            bool a = true;

            if ( a )
            {
                int i = 1;
            }
            i  = "s";
        }
    }
}

Var.cs(13,14): error CS0103: The name 'i' does not exist in the current context

      

Obviously, but what's going on here?

+3


source to share


2 answers


C # requires a simple name to have the same meaning across all blocks that use it first. From here.

From the specification.



For every occurrence of a given identifier as a simple name in an expression or declarator, in the variable localization space of that occurrence, every other occurrence of the same identifier as a simple name in an expression or declarator must refer to the same person. This rule ensures that the meaning of the name is always the same in a given block, switch block, for-, foreach-, or use-statement, or anonymous function.

+3


source


The id i only appears inside the if, but its scope is the whole method. This means that the variable that I am identifying occurs as soon as the method starts. This is because memory must be allocated at this time. The decision about whether to allocate memory on the stack is impossible at runtime and hence all variables inside condition blocks are created before the control enters the if value and the variable exists until the method returns.



-1


source







All Articles