Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

The 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?.

like image 287
morpheous Avatar asked Sep 02 '10 10:09

morpheous


2 Answers

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.

like image 142
Dirk Vollmar Avatar answered Nov 20 '22 16:11

Dirk Vollmar


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.

like image 27
Alex Reitbort Avatar answered Nov 20 '22 17:11

Alex Reitbort