I can write
if(Model.DecisionReason != null && Model.DecisionReason.Length > 35)
return Model.DecisionReason.Substring(0, 32) + "...";
else
return Model.DecisionReason;
and the && comparison in the if will short-circuit, preventing an exception if Model.DecisionReason is null. However, if I write
return (Model.DecisionReason != null && Model.DecisionReason.Length > 35) ?
Model.DecisionReason.Substring(0, 32) + "..." :
Model.DecisionReason;
There is no short-circuit and I hit the exception. Is there a way to make it to short-circuit, or am I forced to either wrap the length comparison in an if check for the null or nest ternaries (not the most readable)?
Both of the code samples you wrote will have identical behavior. It’s not the
ifthat’s short circuiting but simply a core component of the&&expression itself.