CS.METHOD.UNUSED_PRIVATE

Avoid unused private methods.

This rule triggers whenever a 'private' method or property is not used anywhere in the class or any inner class.

Vulnerability and risk

A private method or property that is not used anywhere in the class is essentially dead code. At best, this was code that was left out after some clean up. At worst, it may indicate more important bugs where the private method was supposed to be called from somewhere.

Vulnerable code example

Copy
  using System;
  namespace AvoidUnusedPrivateMethods
  {
      public class Example
      {
          int _myField;
          public Example()
          {
          }
         private int MyInt
         {
             get { return _myField; }
             set { _myField = value; } // VIOLATION
         }
         private Example(int init) // VIOLATION
         {
         }
         private void myTestMethod(int myArg)
         {
         }
         private void mySecondTestMethod(int myArg) // VIOLATION
         {
             myTestMethod(Int32.MaxValue);
         }
         private class MySubType
         {
             Example ex = new Example();
             private void checkValue() // VIOLATION
             {
                 int a = ex.MyInt;
             }
         }
     }
 }

Fixed code example

Copy
  // Fixed by removing unused code or calling the methods.
  
  using System;
  namespace AvoidUnusedPrivateMethods
  {
      public class Example
      {
          int _myField;
         public Example()
         {
             _myField = 55;
         }
         private int MyInt
         {
             get { return _myField; }
         }
         private class MySubType
         {
             Example ex = new Example();
             public int Foo()
             {
             return ex.MyInt;
             }
         }
     }
 }