CS.SWITCH.NODEFAULT

Provide 'default:' for each 'switch' statement.

This rule identifies any "switch" statement that does not have a "default" statement. An error is reported for each occurrence. This rule applies for the C# language only.

Mitigation and prevention

Often, the "case" statements in a switch are the only logical options, so a "default" statement should be added to catch any options that are outside the accepted range of inputs. This can also handle gracefully situations where some additional values are defined in an enum and the switch has case statements for only the earlier values of the enum.

Vulnerable code example

Copy
  public class PDS
  {
      void method (int i)
      {
          switch (i) // VIOLATION: missing default label
          {
              case 0:
                  System.Console.WriteLine ("Zero");
                  break;
         }
     }
 }

Fixed code example

Copy
  // Add a "default" statement.
  public class PDSFixed
  {
      void method (int i)
      {
          switch (i)
          { 
              case 0:
                  System.Console.WriteLine ("Zero");
                 break;
             default: // FIXED
                 break;
         }
     }
 }