- What language is this for?
C# - Which rule?
1125: Boolean literals should not be redundant - Are you using
SonarQube Community Edition Version 10.4 (build 87286)
Consider the case of a Razor layout (.cshtml):
@if (ViewBag.MyFlag == true)
{
<div>Some markup here</div>
}
The property Microsoft.AspNetCore.Mvc.Razor.RazorPageBase.ViewBag
is dynamic
, which means code using it is not checked at compile time.
The above code works if a consuming page sets ViewBag.MyFlag
to an actual bool
value (as it should), but it works even if the page does NOT set the value (I think it is implicitly considered null
).
Removing the explicit boolean check:
@if (ViewBag.MyFlag)
{
<div>Some markup here</div>
}
makes consuming pages explicitly require setting the value to either true
or false
, or else a 500 error happens wit this message:
An unhandled exception occurred while processing the request.
RuntimeBinderException: Cannot convert null to ‘bool’ because it is a non-nullable value type
This issue could be solved in a number of ways:
- strongly typed page models
- explicit boolean casts:
@if (!(bool)ViewBag.MyFlag) {...}
- manual type checking
However in this particular cases I feel using explicit boolean variables is the cleanest and most readable way (save for strongly typed models which we have to investigate) to show that a boolean value is expected in this spot and to handle implicit null
values.
I guess this is not a real false positive and maybe there are better ways to solve it, but it is a case I found and wanted to note.