Answer the question
In order to leave comments, you need to log in
How does the declaration scope rule work in c#?
There is a misunderstanding of how the compiler determines whether a variable can be declared in a given scope or not.
First listing
static void Main(string[] args)
{
int some = 400;
if (some > 100)
{
int ansome = some - 100;
Console.WriteLine(ansome);
}
int ansome = 10000;
Console.WriteLine(ansome);
}
static void Main(string[] args)
{
int some = 400;
if (some > 100)
{
int ansome = some - 100;
Console.WriteLine(ansome);
}
{
int ansome = 10000;
Console.WriteLine(ansome);
}
}
Answer the question
In order to leave comments, you need to log in
https://docs.microsoft.com/en-us/dotnet/csharp/lan...
The lifetime of a local variable is the portion of program execution during which storage is guaranteed to be reserved for it. This lifetime extends at least from entry into the block, for_statement, switch_statement, using_statement, foreach_statement, or specific_catch_clause with which it is associated, until execution of that block, for_statement, switch_statement, using_statement, foreach_statement, or specific_catch_clause ends in any way. (Entering an enclosed block or calling a method suspends, but does not end, execution of the current block, for_statement, switch_statement, using_statement, foreach_statement, or specific_catch_clause.) If the local variable is captured by an anonymous function (Captured outer variables), its lifetime extends at least until the delegate or expression tree created from the anonymous function,
The point is that we declare (and sometimes immediately initialize) a variable once and use it in the current and nested blocks.
static void Main(string[] args)
{
int some = 400;
int ansome;
if (some > 100)
{
ansome = some - 100;
Console.WriteLine(ansome);
}
ansome = 10000;
Console.WriteLine(ansome);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question