C# false positive with pattern matching on switch-case

Hi, I believe pattern matching in a switch-case code is throwing a false-positive, specifically on the bool _ pieces

  • ALM used: Azure DevOps
  • CI system used: Azure DevOps
  • Languages of the repository: C#
  • Error observed: Code Smell: Change this condition so that it does not always evaluate to 'True'. (csharpsquid:S2589)
  • Steps to reproduce (code example):
string contentPageId = contentPage.TemplateID.ToString().ToLower();

switch (true)
{
    case bool _ when contentPageId.Equals(EventPage.TemplateIdString, StringComparison.InvariantCultureIgnoreCase):
        text = "Register now";
        break;
    case bool _ when contentPageId.Equals(NewsPage.TemplateIdString, StringComparison.InvariantCultureIgnoreCase):
        text = "Find out more";
        break;
    case bool _ when contentPageId.Equals(MemberNoticePage.TemplateIdString, StringComparison.InvariantCultureIgnoreCase):
        text = "Download notice";
        break;
    default:
        return string.Empty;
}

Hi @linasw, welcome to Sonar Community!

I reviewed the snippet you provided and it seems a true positive to me.
The rule is suggesting to remove the bool keyword, because true is always boolean.

string contentPageId = contentPage.TemplateID.ToString().ToLower();

switch (true)
{
    case var _ when contentPageId.Equals(EventPage.TemplateIdString, StringComparison.InvariantCultureIgnoreCase):
        text = "Register now";
        break;
    case var _ when contentPageId.Equals(NewsPage.TemplateIdString, StringComparison.InvariantCultureIgnoreCase):
        text = "Find out more";
        break;
    case var _ when contentPageId.Equals(MemberNoticePage.TemplateIdString, StringComparison.InvariantCultureIgnoreCase):
        text = "Download notice";
        break;
    default:
        return string.Empty;
}

I see, thanks for the reply.

So does that mean that pattern matching in this case is a no-go? I was trying to adapt to my code what I found in Stackoverflow here. I didn’t want to end up with a long list of if-else, so wanted to give it a try with a switch-case as shown in the answer in Stackoverflow

Hi,

I would use something like String.ToUpperInvariant.

Cheers

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.