Search code examples
c#asp.netasp.net-coresonarqube

Remove the unnecessary Boolean literal(s) issue in SonarQube - C#


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?


Solution

  • 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.