GurdeepS
GurdeepS

Reputation: 67213

How is this if statement interpreted?

I saw the code below, which shocked everyone.

How is this code executed?

if (!Test.IsXyz == true)
{ }

If IsXyz resolves to true but then to false with the ! operator, how is this code interpreted? Because the RHS states true. Would this be:

1) False for LHS | True for RHS == False (From my truth table days)

Assuming the bool resolves to true, I can imagine several wierd ways this code would be understood. What is the official way to the compiler?

Upvotes: 0

Views: 131

Answers (4)

Simeon Pilgrim
Simeon Pilgrim

Reputation: 25903

Order dose not really matter here

as you ether have !( L == R) or (!L) == R, but that equals the same thing as can been seen

 L = T : !( T == T) -> !( T ) -> F or (!T) == T -> F == T -> F

and

 L = F : !( F == T) -> !( F ) -> T or (!F) == T -> T == T -> T

Upvotes: 0

zebrabox
zebrabox

Reputation: 5764

The statement is a more verbose, though equally valid, equivalent to

if (!Test.IsXyz)
{
}

So if the result if false then the result of the condition is true.
If the result is true then the result of the condition is false.

Upvotes: 1

Joe
Joe

Reputation: 42597

According to C# operator precedence, this should be evaluated as

((!Test.IsXyz) == true)

thus False (LHS) and True (RHS).

Upvotes: 2

CesarGon
CesarGon

Reputation: 15325

Evaluates to false.

In other words, the code:

var Test = new { IsXyz = true };

if (!Test.IsXyz == true)
{
    Console.WriteLine("TRUE");
}

does not print anything on the screen.

Upvotes: 1

Related Questions