CS.SWITCH.DEFAULT.POSITION

Default label does not appear as the first or the last label in switch statement.

The default label is not at the beginning or end of a switch statement.

Vulnerability and risk

If the default label is not placed at the beginning or end of a switch statement, maintainability may be impaired, or incorrect coding may cause unintended behavior.

Mitigation and prevention

Place the default label at the beginning or end of a switch statement.

Example

Copy
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace kmcustom
  {
      class C03
     {
         /* default located at first */
         public void testOK1(int num)
         {
             switch (num)
             {
                 default: //OK
                     break;
                 case 1:
                     break;
                 case 2:
                     break;
 
             }
         }
 
         /* default located at last */
         public void testOK2(int num)
         {
 
             switch (num)
             {
                 case 1:
                     break;
                 case 2:
                     break;
                 default: //OK
                     break;
             }
         }
 
 
         /* default located in the middle */
         public void testNG1(int num)
         {
             switch (num)
             {
                 case 1:
                     break;
                 default://NG
                     break;
                 case 2:
                     break;
             }
 
         }
 
         /* no default */
         public void testNG2(int num)
         {
             switch (num) //NG
             {
                 case 1:
                     break;
                 case 2:
                     break;
             }
 
         }
 
     }
 }