views:

121

answers:

4

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

+11  A: 

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.

0xA3
Good explanation (+1), but funny how 3 out of 5 answers write "loose" instead of the correct "lose" :-)
Gorpik
@Gorpik: Thanks for the correction. For me as non-native speaker it's always hard to get this right ;)
0xA3
+1: the answer is encapsulated in this statement: "there is a code path where text is not assigned to ..."
morpheous
Wouldn't it be better to initialize as text=string.empty ? than using null
Aneef
+4  A: 

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.

Alex Reitbort
A: 

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:

http://stackoverflow.com/questions/1542824/c-initialization-of-instance-fields-vs-local-variables

flq
A: 
     // 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.
swapneel