Looking at the following code we have a “simple” switch, with a check whether the passed enum is defined, followed by the switch handling the passed enum. We believe that the default is mandatory and that the compiler should insist on its existence, to avoid the developer forgetting to handle any “new” defined enums, which pass the first test, but would fall through in terms of the switch without anyone knowing.
Are we breaking best practices by insisting that developers add the default: case?
static void TestSwitch( Robot robot )
{
if ( Enum.IsDefined ( typeof(Robot), robot ) )
{
switch ( robot )
{
case Robot.Red:
Console.WriteLine ( "Red ... stop" );
break;
case Robot.Orange:
Console.WriteLine ( "Orange ... stop if outside barrier" );
break;
case Robot.Green:
Console.WriteLine ( "Green ... go, go, go." );
break;
// if we remove the break, we can have a situation where processing
// is successful, but not as expected.
default:
Console.WriteLine ( "Oh, oh, unhandled event: " + robot.ToString() );
break;
}
}
}