Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a `while` loop, why can't I declare variable in the condition as in a `for` loop? [duplicate]

Tags:

c#

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++)
like image 283
colinfang Avatar asked Aug 21 '11 22:08

colinfang


3 Answers

You can still use for:

for (string line; (line = sr.ReadLine()) != null; )
    ...
like image 169
hammar Avatar answered Nov 14 '22 17:11

hammar


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.

like image 9
Domenic Avatar answered Nov 14 '22 15:11

Domenic


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

like image 2
nycdan Avatar answered Nov 14 '22 17:11

nycdan