Our website uses cookies to enhance your browsing experience.
Accept
to the top
>
>
>
V3139. Two or more case-branches...
menu mobile close menu
Additional information
toggle menu Contents

V3139. Two or more case-branches perform the same actions.

Sep 24 2019

The analyzer has detected that multiple case clauses of the switch statement contain the same code. It may often indicate redundant code and can be improved by merging the labels. Identical code fragments may also be copy-paste errors.

The example of a redundant code:

switch (switcher) 
{
  case 0: Console.Write("0"); return;
  case 1: Console.Write("0"); return;
  default: Console.Write("default"); return;
}

Different switcher values may trigger the same actions, so the code can be simplified:

switch (switcher) 
{
  case 0:
  case 1: Console.Write("0"); return;
  default: Console.Write("default"); return;
}

Using the pattern matching in case disable grouping expressions under one statement.

private static void ShowCollectionInformation(object coll, bool cond)
{
  switch (coll)
  {
    case Array arr:
      if(cond)
      {
        Console.WriteLine (arr.ToString());
      }
      break;
    case IEnumerable<int> arr:
      if(cond)
      {
        Console.WriteLine (arr.ToString());
      }
      break;
   }
}

To facilitate modifying and debugging in the future, move the code into a separate method.

The next example, taken from a real application, demonstrates an error:

switch (status.BuildStatus)
{
  case IntegrationStatus.Success:
    snapshot.Status = ItemBuildStatus.CompletedSuccess;
    break;
  case IntegrationStatus.Exception:
  case IntegrationStatus.Failure:
    snapshot.Status = ItemBuildStatus.CompletedSuccess;
    break;
}

The status assignment is incorrect: the ItemBuildStatus enumeration contains CompletedFailed that should be assigned in the IntegrationStatus.Failure case when an error or exception occurs.

The fixed code:

switch (status.BuildStatus)
{
  case IntegrationStatus.Success:
    snapshot.Status = ItemBuildStatus.CompletedSuccess;
    break;
  case IntegrationStatus.Exception:
  case IntegrationStatus.Failure:
    snapshot.Status = ItemBuildStatus. CompletedFailed;
    break;
}

You can look at examples of errors detected by the V3139 diagnostic.