Possible Duplicate:
why can't we define a variable inside a while loop?
I would like to simplify the following code:
string line;
while ((line = sr.ReadLine()) != null)
into:
while ((string line = sr.ReadLine()) != null)
but failed.
However, we surely can do this in for
:
for (int i=0, int n=50;i<n;i++)
You can still use for
:
for (string line; (line = sr.ReadLine()) != null; )
...
Since the while
loop takes a condition, what this would do is declare a new instance of line
every time the loop is run, because the condition is evaluated every time through the loop.
It works in a for
loop because the initializer (the first of the three semicolon-separated expressions) is run only once, at the start; the condition is the second expression. You would have the same problem trying to declare a variable in the condition expression of a for
loop.
I believe the reason is that you would be declaring the variable multiple times (each pass of the loop).
Asked and answered in more detail here: Same question
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With