Reputation: 435
double number;
bool isParsed = false;
while(!isParsed)
{
Console.WriteLine("Enter the value");
isParsed = double.TryParse(Console.ReadLine(), out number);
if(isParsed)
{
break;
}
Console.WriteLine("Invalid value");
}
A friend and I were studying this code block. I found this part to understand:
bool isParsed = false;
while(!isParsed)
I thought that if isParsed = false, and the while loop will check the negation (!isParsed) to see if it should run, wouldn't this be the logic:
while(!isParsed) => while(NOT(false)) => while (true)?
Therefore, the while loop would never run. But it does run. Later I understood that a check was happening:
while (!isParsed) => while((!isParsed) == true),
but he says that not exactly what is happening.
Can someone explain what is happening here?
Upvotes: 1
Views: 69
Reputation: 3696
bool isParsed = false;
while(!isParsed)
Loop should run, at least once; Which is correct behavior, since your condition is evaluating to true.
Upvotes: 1
Reputation: 251
When using a boolean in an expression you are checking for a value of true. When adding the logical NOT operator, you are now looking for a value of false.
while (false)
Upvotes: 2
Reputation: 5862
You're saying it correctly: while (true)
. That true boolean condition denotes that the next (and first) iteration will run.
!false == true
Take a look at the MSDN documentation stating the behavior of the while loop: https://msdn.microsoft.com/en-us/library/2aeyhxcd.aspx
Upvotes: 4