Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Ok, so I know it sounds a little strange but someone was telling me that you can assign a value AND check for null in a while clause i.e
C#
string line;
StreamReader sr = new StreamReader("some file");
while(line = sr.ReadLine() != null)
{
    // do something with line
}


Doesn't look or sound right, but it would be a nice short cut over:

C#
string line;
StreamReader sr = new StreamReader("some file");
line = sr.ReadLine();
while(line != null)
{
    // do something with line
    line = sr.ReadLine();
}
Posted
Updated 7-Sep-10 22:48pm
v3
Comments
Chris Maunder 7-Sep-10 22:48pm    
You can. You can also write code that's easily read by all levels of programmers that may need to touch your code. I prefer clarity to cleverness.
Dalek Dave 8-Sep-10 4:48am    
Edited for Grammar.
Adam R Harris 8-Sep-10 10:46am    
Have to agree with you Chris.... just nice to know. However I’m not entirely sure that you sacrifice clarity with this particular brand of cleverness, but as a whole I have to agree that clarity is much more important than cleverness.

1 solution

Close, missing a set of parentheses
while( (line = sr.ReadLine()) != null)
 
Share this answer
 
Comments
Adam R Harris 7-Sep-10 21:05pm    
Figures .... all this time .... time to update the code :)
Dalek Dave 8-Sep-10 4:48am    
Well Spotted.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900