I know this is a very newbie C# question but I am implementing a small program which does the following:
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
bool isRun = false;
int number = 0;
while (isRun = (true) && number < 3)
{
++number;
Console.WriteLine("Number = {0}", number.ToString());
Console.WriteLine();
}
Console.WriteLine(isRun.ToString());
Console.ReadLine();
}
}
}
At the end of the while loop, I would have expected the bool value to be true, but is is printed to be false. Why is that? Is this different from C++ where I would have done something like and the same thing in C# is giving me false
while(number<3)
{
is = true;
}
if(is){
cout<<true;
}
The reason you’re seeing this behavior is due to the operator precedence involved. Here the
&&binds more strongly than=so the code in the loop is actually bound as the followingOnce
number > 3the&&expression isfalseand is assigned into theisRunvalue and simultaneously terminates the loop. Hence once the loop exits you will seeisRunasfalseTo get the behavior you are looking for you will need to manually correct the precedence with parens.
Note: In general, as @Servey pointed out, the assignment of locals to expressions inside the loop predicate is considered bad practice. Many C# users would actually be surprised that code compiles at all because they’ve been conditioned to only use
==in loops.It’s more idiomatic to simply set
isRuntotrueon the first line of the loop for this pattern.