CS.STMT.CONTROL.EMPTY

Avoid control statements with empty bodies.

This rule identifies "if", "for", "while", "do while", "else" and "switch" statements with empty bodies. An error is reported for each occurrence.

Mitigation and prevention

A conditional statement that is immediately followed by a closing statement (e.g. a semicolon) is usually a typo. Following this rule prevents hard-to-detect bugs from entering into the codebase. Another situation that often leads to statements with empty bodies is when a developer decides to postpone the handling of a condition and forgets to get back to it before the release. This can lead to missing out handling important conditions that can even cause security holes.

Vulnerable code example

Copy
  using System;
  namespace PB.EB
  {
      public class EB
      {
          void method (int i)
          {
              if (i < 0) ; // VIOLATION
              Console.WriteLine("negative i"); // This always gets printed
         }
         public static void Main()
         {
             // ...
         }
     }
 }
 // The 'WriteLine()' statement will always be executed regardless
 // of the value of 'i'.

Fixed code example

Copy
  // Remove the unnecessary semicolon.
  using System;
  namespace PB.EB
  {
      public class EB
      {
          void method (int i)
          {
              if (i < 0) // FIXED
             {
                 Console.WriteLine("negative i");
             }
         }
         public static void Main()
         {
             // ...
         }
     }
 }