Variable scope in C #

I read "C # Start" to update my memory in C # (C ++ background).

I found this snippet in a 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 above snippet will not compile, because according to the book, the variable text is not initialized (initialized only initialized in the loop), and the last value assigned to it is lost when the loop exits.

I cannot understand why the value assigned to the value of L is lost only because the area in which the value of R was created was displayed - although the value of L is still in scope.

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

+6
c # compiler-errors
source share
4 answers

A variable does not "lose" its meaning. You get a compiler error because there is a path to the code where text not assigned (the compiler cannot determine if the loop body is entered or not. This is a limitation to avoid too 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 to the for statement. This is best practice since the variable should be declared in the smallest possible scope of the declaration.

+12
source share

This does not compile, not because text will lose value after exiting for , but because the compiler does not know whether you enter for or not, and if you do not then text will not be initialized.

+4
source share

Sorry, but the value is not lost on my machine ...

Here, the question of whether the compiler permits to be uninitialized or not may be somewhat relevant:

Initialization of instance fields compared to local variables

0
source share
  // 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
source share

All Articles