C #: Why is this variable in scope and out of scope at the same time?

Possible duplicate:
C # variable zoom

I ran into something that I had never encountered. I am not looking for a fix because I know how to solve it. What I would like to know is what the compiler does. This is just a sample code:

if (true) { int x = 0; } int x = 0; 

This code generates the error "Local variable" x "cannot be declared in this area because it will have a different value of" x ".

However, I am changing the code to this:

 if (true) { int x = 0; } x = 0; 

I get the error "Unable to resolve the character" x ".

So what is going on here? How is it that x is both a scope and inoperable?

+4
source share
2 answers

A variable scope is the entire block in which it is declared. However, you cannot link to it before the announcement.

Eric Lippert has a blog post about this in more detail. EDIT: And as Eric points out, one more ...

+5
source

Its not , simply because C # allows you to declare / define variables anywhere in the program, its scope is the entire block in which it is declared, and therefore it does x predeclared / (in scope) for x in the if block

0
source

Source: https://habr.com/ru/post/1346090/


All Articles