In your opinion what is more readable: ?? (operator) or use of if's

后端 未结 13 1989
谎友^
谎友^ 2021-01-21 07:05

I have a method that will receive a string, but before I can work with it, I have to convert it to int. Sometimes it can be null and I ha

13条回答
  •  渐次进展
    2021-01-21 07:30

    [Assuming you only need to check for null, and not empty string also, as others have pointed out]

    The semantic difference between the two is that ?? is an expression, while if is a statement. An expression says "perform a calculation and return a result", exactly the semantics you seek. More work has to be done to allow an if statement to express the same semantics; beyond that, the if leaves room for more logic than the calculation, room you don't need.

    You should use the ?? operator because it expresses exactly the desired intent.

提交回复
热议问题