Fred Smith
Fred Smith

Reputation: 2139

C# How to merge the default case statement with one switch statement?

I work on a 4.5.2 .NET Framework solution with Visual Studio 2017 Here is my code:

case "medium":
    font1.Size = 14; 
    font1.RGBColor = Color.Black;
    font1.Bold = false;
    break;
default:
    font1.Size = 14; 
    font1.RGBColor = Color.Black;
    font1.Bold = false;
    break;

VS is telling me to merge the default case with the "medium" case so I write this:

case "medium":
default:
    font1.Size = 14; 
    font1.RGBColor = Color.Black;
    font1.Bold = false;
    break;

but now VS is telling me to remove the empty "medium" case so I write this:

default:
case "medium":
    font1.Size = 14; 
    font1.RGBColor = Color.Black;
    font1.Bold = false;
    break;

But again VS is telling to remove the empty "medium" case. So how can I merge the default case with one existing?

Upvotes: 2

Views: 1265

Answers (2)

golakwer
golakwer

Reputation: 373

This is not a direct answer to how to merge a case with the default case. This is more of a how to organize you code better to avoid this situation.

If the sample code is indeed real code that is part of your solution, perhaps organizing it a different way would make it easier to manage.

before the case statement give font1 the default values

font1.Size = 14; 
font1.RGBColor = Color.Black;
font1.Bold = false;

then in the case statement leave off the default clause

case "medium":
    font1.Size = 14; 
    font1.RGBColor = Color.Black;
    font1.Bold = false;
    break;

the values will be the default if no case statement match

this way you dont run into warnings

also doing it this way, in certain situations, is superior to having a default case, for example imagine that "small" only needs to set the Size to 10 but keep the default RGBColor and Bold, doing it this way would not require setting those values in the case statement, those values could fall through from above

Upvotes: -1

Marc Gravell
Marc Gravell

Reputation: 1064204

Option 1:

Ignore VS. It isn't in charge, you are. If it is clearer to keep it: keep it. You can use various options to suppress the message to stop it messing up your nice clean build.

Option 2:

default: // note: includes "medium"

Upvotes: 4

Related Questions