Is there a way to short-circuit a ternary operation?

孤人 提交于 2020-01-04 03:53:06

问题


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)?


回答1:


Both of the code samples you wrote will have identical behavior. It's not the if that's short circuiting but simply a core component of the && expression itself.



来源:https://stackoverflow.com/questions/10128110/is-there-a-way-to-short-circuit-a-ternary-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!