Lets say if there is a boolean variable status. Assume status has value false.
I would like to know what is the difference between
if ( status = true )
{
//block of code
}
if ( status == true )
{
//block of code
}
I’ve tried to understand it by writing a sample program, the code in the first if block gets executed for whatever the value status is having (true or false).
For other primitive types, system throws compile time error if I use only one “=” in if and why it doesn’t throw the error in case of boolean type. Thanks.
The first one is not a comparison, it is an assignment. The reason it compiles is that it assigns a boolean value, so the result of the assignment is also a boolean value.
The first statement assigns
statusa new value, and executes theifaccording to that new value (truein your case). The second statement compares the current value ofstatusto the value on the right, and acts on the result of the comparison.Note that is it never a good idea to compare
booleanin Java orboolin C# totrueorfalse: you can useif (status)instead ofif (status == true)andif (!status)instead ofif (status == false). This, however, does not hold for nullable types in C#, so comparingbool?totrueorfalseis often a good idea.