开发者

Variable scope in C#

I am reading Beginning C# to refresh my memory on C# (background in C++).

I came across this snippet in the book:

int i;
string text;
for (i = 0; i < 10; i++)
{
   text = "Line " + Convert.ToString(i);
   Console.WriteLine("{0}", text);
}
Console.WriteLine("Last text output in loop: {0}", text);

T开发者_Python百科he snippet above will not compile - because according to the book, the variable text is not initialized, (only initialized in the loop - and the value last assigned to it is lost when the loop block is exited.

I can't understand why the value assigned to an L value is lost just because the scope in which the R value was created has been exited - even though the L value is still in scope.

Can anyone explain why the variable text loses the value assigned in the loop?.


The variable does not "lose" its value. You get the compiler error because there is a code path where text is not assigned to (the compiler cannot determine whether the loop body is entered or not. This is a restriction to avoid overly-complex rules in the compiler).

You can fix this by simply setting text to null:

string text = null;
for (int i = 0; i < 10; i++)
{
   text = "Line " + Convert.ToString(i);
   Console.WriteLine("{0}", text);
}
Console.WriteLine("Last text output in loop: {0}", text);

Note that I also moved the declaration of the loop index variable i into the for statement. This is best-practice because variable should be declared in the smallest possible declaration scope.


This does not compile not because text looses it's value after you exit for, but because compiler does not know if you will enter for or not, and if you not then text will not be initialized.


Sorry, but the value doesn't get lost on my machine...

Somewhat relevant may be this question here about what the compiler allows to be uninitialized vs. what not:

Initialization of instance fields vs. local variables


     // Your code has compile time error - Use of unassigned local variable 'text'  
     //'text' variable hold last value from loop On Execution time not on Compile time.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜