Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

C# variable scoping: 'x' cannot be declared in this scope because it would give a different meaning to 'x'

if(true)
{
    string var = "VAR";
}

string var = "New VAR!";

This will result in:

Error 1 A local variable named 'var' cannot be declared in this scope because it would give a different meaning to 'var', which is already used in a 'child' scope to denote something else.

Nothing earth shattering really, but isn't this just plain wrong? A fellow developer and I were wondering if the first declaration should be in a different scope, thus the second declaration cannot interfere with the first declaration.

Why is C# unable to differentiate between the two scopes? Should the first IF scope not be completely separate from the rest of the method?

I cannot call var from outside the if, so the error message is wrong, because the first var has no relevance in the second scope.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue here is largely one of good practice and preventing against inadvertent mistakes. Admittedly, the C# compiler could theoretically be designed such that there is no conflict between scopes here. This would however be much effort for little gain, as I see it.

Consider that if the declaration of var in the parent scope were before the if statement, there would be an unresolvable naming conflict. The compiler simply does not differentiate between the following two cases. Analysis is done purely based on scope, and not order of declaration/use, as you seem to be expecting.

The theoretically acceptable (but still invalid as far as C# is concerned):

if(true)
{
    string var = "VAR";
}

string var = "New VAR!";

and the unacceptable (since it would be hiding the parent variable):

string var = "New VAR!";

if(true)
{
    string var = "VAR";
}

are both treated precisely the same in terms of variables and scopes.

Now, is there any actual reason in this secenario why you can't just give one of the variables a different name? I assume (hope) your actual variables aren't called var, so I don't really see this being a problem. If you're still intent on reusing the same variable name, just put them in sibling scopes:

if(true)
{
    string var = "VAR";
}

{
    string var = "New VAR!";
}

This however, while valid to the compiler, can lead to some amount of confusion when reading the code, so I recommend against it in almost any case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...