Re: simple example
- From: "Patrice" <http://scribe-en.blogspot.com/>
- Date: Wed, 16 Sep 2009 13:47:43 +0200
This is unrelated with static int x=123.
This is because you declared a local variable x at some point in your code.
But technically speaking a local variable is tied with the current block of
code (or more precisely function) as if all declarations were at the top of
your function.
So using x even before the declaration means that you are trying to use
"x_the_local_variable" (and not only below the point where it is declared as
you perhaps thought). The compiler then tells :
"Cannot use local variable 'x' before it is declared."
With this :
static void Main(string[] args)
{
int x = 1;
{ int x = 1; }
}
You'll get :
A local variable named 'x' cannot be declared in this scope because it would
give a different meaning to 'x', which is already used in a 'parent or
current' scope to denote something else
but is once again unrelated to static int x=123. This is because a local
variable is tied to the current function so even though it is in a inner
block of code, you still have two x local variables named the same way in
this function which is not possible...
An important part from the error message is *local variable* i.e. it is
forbidden because this is another local variable. You are still free to use
the same name for something else (such as a static member) in a parent
scope... I believe this is what could have caused the initial confusion.
So to summarize :
- a local variable is scoped to the current function (even if declared in an
inner block of code inside the function such as a loop) and should be
uniquely named inside this function
- it should be declared before being used (and declaring a variable
somewhere else than at the top of a function is just a conveniance, it
doesn't mean that what is in the current scope changes at this exact point,
technically speaking all local variable declaration are handled as if they
were at the top of the function)
- you are allowed to declare a local variable (so by definition scoped to
the function) and other members tied to other classes with the same name as
you'll always be able to access this last one by using a fully qualified
name...
--
Patrice
.
- References:
- simple example
- From: Tony Johansson
- Re: simple example
- From: Patrice
- Re: simple example
- From: Tony Johansson
- simple example
- Prev by Date: Re: simple example
- Next by Date: Re: simple example
- Previous by thread: Re: simple example
- Next by thread: Re: simple example
- Index(es):
Relevant Pages
|