Question about C# scope rules [Archive] - C Board

PDA

View Full Version : Question about C# scope rules


converge
01-28-2002, 11:08 PM
I was wondering what the fundamental difference is between C# scope rules of local variables and Java's. I know there is a difference, but I can't figure it out. Here is the scope rule from the C# language definition:
"The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs. It is a error to refer to a local variable in a textual position that precedes the variable declarator of the local variable."

Java:
"The scope of a local variable declaration in a block (§14.4.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement. "

It seems to me that the only difference is that Java states more explicitly that a local variable can be seen later in the variable declaration statement. I don't see how the C# definition would exclude the variable declaration statement, but that is the only difference I can see.

nvoigt
01-29-2002, 01:21 AM
To me both texts seem to say the same. Declare a local variable, which is valid in the block it was declared below or on the same line as the declaration.

converge
01-29-2002, 09:25 AM
Yea, thats what I thought too. However, my professor insists there is a difference, and he wants us to figure it out.

nvoigt
01-30-2002, 06:56 AM
Well, being extremly nitpicky, you can see differences.

The scope of the C# variable is the whole block. The compiler will flag an error if you refer to the variable before the line of declaration.

The scope of the Java variable is from the line of declaration down to the end of the current block.

This leads to two different conclusions:

a) Two people wrote two documents and while they meant the same, each has it's own way of finding words and building sentences.

b) C# creates the variable at block start, the compiler hinders you to access it before the line of declaration while Java creates it at the time it is declared.

For the compiler however, these two versions work exactly the same.