Thoughts about S1125 and `dynamic`

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.

1 Like

Hello @m-gallesio

Thank you for reporting this. I can confirm this as a false positive and added an issue and a reproducer to our backlog Fix S1125 FP: dynamic and custom nullable structs with conversion to bool are compliant · Issue #8995 · SonarSource/sonar-dotnet · GitHub.

1 Like