Reputation: 16926
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?.
Upvotes: 6
Views: 288
Reputation: 176159
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.
Upvotes: 12
Reputation: 3061
// 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.
Upvotes: 0
Reputation: 22829
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
Upvotes: 0
Reputation: 13696
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.
Upvotes: 4