What is the difference between comparing a Boolean value with a Boolean variable using = and ==?

advertisements

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 status a new value, and executes the if according to that new value (true in your case). The second statement compares the current value of status to the value on the right, and acts on the result of the comparison.

Note that is it never a good idea to compare boolean in Java or bool in C# to true or false: you can use if (status) instead of if (status == true) and if (!status) instead of if (status == false). This, however, does not hold for nullable types in C#, so comparing bool? to true or false is often a good idea.