Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope variable inside if [duplicate]

Tags:

c#

Possible Duplicate:
C# Variable Scoping

I thought I may declare two variables with the same name if in different scope:

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

That would mean i declared inside the if is visible outside ( that's what I understood )

But if I try to use it then 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?

like image 886
OscarRyz Avatar asked Jul 17 '26 01:07

OscarRyz


1 Answers

C# requires that a simple name have one meaning throughout all the blocks which first uses it.From here.

From Specification.

For each occurrence of a given identifier as a simple-name in an expression or declarator, within the local variable declaration 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 entity. This rule ensures that the meaning of a name is always the same within a given block, switch block, for-, foreach- or using-statement, or anonymous function.

like image 116
Sandeep Avatar answered Jul 19 '26 15:07

Sandeep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!