Reputation: 4864
IsSaveNew
is type of bool?
CoverLetterId
is type of int?
if (coverLetter.IsSaveNew ?? true || coverLetter.CoverLetterId == null)
coverLetter.CoverLetterId == null
. This statement is marked as unreachable in visual studio(2012).
But if IsSaveNew
was false, then it would reach at the second condition. Why Visual Studio says so?
Upvotes: 1
Views: 127
Reputation: 98740
||
has highger precedence than ??
operator.
Check out 7.2.1 Operator precedence and associativity
Your true || coverLetter.CoverLetterId == null
works first. If you want coverLetter.IsSaveNew ?? true
should work first, just use parentheses around it.
Like;
if ((coverLetter.IsSaveNew ?? true) || coverLetter.CoverLetterId == null)
But still visual studio says its unreachable
That means (probably) your coverLetter.IsSaveNew ?? true
returns true
, that's why your second operand doesn't evaluate.
From || Operator (C# Reference)
If the first operand evaluates to true, the second operand isn't evaluated. If the first operand evaluates to false, the second operator determines whether the OR expression as a whole evaluates to true or false.
Upvotes: 3
Reputation: 1658
You can put coverLetter.IsSaveNew ?? true in paranthesis to solve this. like-
if ((coverLetter.IsSaveNew ?? true) || coverLetter.CoverLetterId == null)
Upvotes: 1
Reputation: 156918
You'd better use GetValueOrDefault as the ?? part will always evaluate to true
Upvotes: 0
Reputation: 262919
Looks like an operator precedence issue. Your statement is evaluated as:
if (coverLetter.IsSaveNew ?? (true || coverLetter.CoverLetterId == null))
So the right-hand operand to the ||
operator will never be evaluated since its left-hand operand is the literal true
.
You can add parentheses to solve this problem:
if ((coverLetter.IsSaveNew ?? true) || coverLetter.CoverLetterId == null)
Upvotes: 6