Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while() without {}?

Tags:

c#

I had this code in a project in VS2010 - it was a placeholder method I hadn't fully implemented yet. I started the implementation today. Notice there are no {} surrounding the if/else for the while statement. This compiled many times - it has been that way for quite some time. Is this a bug in VS? I thought loops all needed {}

private void ParsefCIPProfiles(string block)
{
 StringReader reader = new StringReader(block);
 string readline = reader.readline();

 while (readline != null)
  if ()
  {}
  else
  {}
}
like image 622
David Green Avatar asked Nov 29 '22 09:11

David Green


2 Answers

Only if there is more than one statement and you want all of those statements to be part of the loop.

Here there is only one if...else statement and that is part of the loop. Anything after that will not be part of the loop and if you want more statements, enclose them in {..}

This is the case with for, if, etc.

like image 40
manojlds Avatar answered Nov 30 '22 23:11

manojlds


No, it isn't a bug. In fact for single-statement contents, most other scoped statements also don't require the curly braces. For instance:

//This is valid
using (var f = new foo)
    f.Bar();

// So is this
foreach (var i in someInts)
    Console.Out.WriteLine(i);
like image 54
Chris Shain Avatar answered Nov 30 '22 21:11

Chris Shain