No, this is not my homework.
(Because there is a stack of answer sheets beside me, waiting to be marked.)
Q: If a local variable in a method has the same name as a variable in the main program, what will occur?
a) an error is generated
b) the variable in the main program is “hidden” until the method is finished executing
c) the variable in the main program will override the variable from the method
d) None of the above.
And the textbook answer is b, quite straightforward.
But on a second thought, is it really “hidden”?
As far as I know, in pure object-oriented languages like C# and Java,
we can always use
this.x
or
MainProgram.x
for static variables.
So my question is:
Can option b be considered true for C#? Why?
Please share your thoughts.
Yes, the local variable
xhides (or more precisely, shadows – thanks to @pst) the member variablexwithin the scope of that method / block. You can refer to the latter with its qualified name asthis.x, to make life easier, but nevertheless the answer is correct. A (fully) qualified name is not scope-dependent anymore so it can’t be hidden or shadowed.