Null-conditional operator always true in if statement when should be false

Jason

When using a null-conditional operator the first if statement will always output True, however the second if statement will output False when using parentheses. Why is the first if statement True?

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new Test { Boolean = true };

            //True
            if (test?.Boolean ?? true && 1 == 2)
                Console.WriteLine("True");
            else
                Console.WriteLine("False");

            //False
            if ((test?.Boolean ?? true) && 1 == 2)
                Console.WriteLine("True");
            else
                Console.WriteLine("False");
        }
    }

    public class Test
    {
        public bool? Boolean { get; set; }
    }
}
Vladimir Arustamian
x ?? y – returns x if it is non-null; otherwise, returns y.

test?.Boolean is x in the first case and (true && 1 == 2) is y.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why is if statement returning false when it should be true?

An and statement returns True when it should return False

$and operator always return true even though i think it should be false

always false conditional statement - sonarqube

Javascript if statement come back false when it should be true

Null-conditional operator and if statement

has() always true when using null coalesce operator?

Flutter conditional statement always renders the true

Javascript: False if statement always evaluates as true

If or statement not returning true when it should be

javascript form validation always returns true even when condition matches and should returns false

VB.NET - List.Contains always returns false when it should be true

Bash: 'if' statement always seems to evaluate first condition as true even when false

Why is the .NET null conditional operator not returning false when trying to check if a collection has any items?

When is self statement true and when is false?

passport's req.isAuthenticated always returning false, even when I hardcode done(null, true)

Does null conditional operator always break on first null ocurrence?

Ternary Operator Outputting True Option when False

Conditional statement always returns false (inline-style)

PHP Bitmask says true when it should be false

regex returns false when should return true

LINQ Query returns false when it should be true

Python "==" returning False when it should return True

Bool = true when it should = false in C++

Excel IF AND statement returning false when true

if statement executing when it is either false or true

Why is my if statement not evaluating false when it should be?

If statement never evaluates false when it should

Why the if statement is false as ~0 is 1 which is 1==1 should be true?