英文:
Remove the unnecessary Boolean literal(s) issue in SonarQube - C#
问题
SonarQube对我的C#(v10)控制器类中的以下两个三元表达式抛出错误,错误信息是Remove the unnecessary Boolean literal(s).
:
IsSuccess = response == null ? false : true;
ResponseMessage = resp == true ? "Success" : "Failure",
我了解Null-合并/Null-合并-赋值运算符可以像这样使用:
variable ??= expression;
这是以下代码的缩写形式:
if (variable is null)
{
variable = expression;
}
我可以在我的三元表达式中使用相同的方法吗?
英文:
SonarQube is throwing an error for the following 2 ternary expressions in my C#(v10) controller class citing Remove the unnecessary Boolean literal(s).
:
IsSuccess = response == null ? false : true;
ResponseMessage = resp == true ? "Success" : "Failure",
I understand that Null-Coalescing / Null-Coalescing-Assignment operator can be used like:
variable ??= expression;
which is a shorthand for:
if (variable is null)
{
variable = expression;
}
Can I make use of the same in my ternary expressions also?
答案1
得分: 4
我认为你遇到这个问题是因为你可以将它重写为
IsSuccess = response != null;
对于第二个表达式,你可以将它重写为
ResponseMessage = resp ? "Success" : "Failure";
三元运算符只需要在?
的左边期望一个布尔值,所以如果值已经是布尔型,你无需再进行测试。
英文:
I think you are getting this issue as you can rewrite
IsSuccess = response == null ? false : true;
As
IsSuccess = response != null;
For the second expression you can rewite
ResponseMessage = resp == true ? "Success" : "Failure";
As
ResponseMessage = resp ? "Success" : "Failure";
The ternary operator is just expecting a bool on the lefthand side of the '?' as such if the value is already a bool you have no need to test it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论