This is probably pretty subjective, but how do people generally lay out their loop control in C# when the control variable is updated in the loop? The pedant in me doesn’t like the separate declaration and repetition involved. eg.
string line = reader.ReadLine();
while (line != null)
{
//do something with line
line = reader.ReadLine();
}
The C coder in me wants to change this to
while (string line = reader.ReadLine() != null)
{
//do something with line
}
but C#’s expressions don’t seem to work that way 🙁
You can’t declare a variable inside an expression.
You can write
To make it clearer, I prefer to write
However, the best alternative is
This will perform equivalently.
If you’re reading some other stream, you can create an extension method that uses the previous syntax to enable
foreachloops.