The analyzer has detected a switch statement whose different case labels contain the same code. This is often a sign of redundant code, which could be improved by merging the labels. However, identical code fragments may also result from copy-paste programming, in which case they are genuine errors.
The following example illustrates the redundant code scenario:
switch (switcher)
{
case 0: Console.Write("0"); return;
case 1: Console.Write("0"); return;
default: Console.Write("default"); return;
}
Indeed, different values of 'switcher' may require performing the same actions, so the code can be rewritten in a more concise form:
switch (switcher)
{
case 0:
case 1: Console.Write("0"); return;
default: Console.Write("default"); return;
}
If you use the case expressions, you won't be able to group such expressions under one condition.
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;
}
}
You can, however, move the code into a separate method, which will make it easier to modify and debug this code in the future.
Now, the following real-life example demonstrates a programming mistake:
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 faulty: the 'ItemBuildStatus' enumeration has the element 'CompletedFailed', which was to be assigned in case of failure or exception.
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. |