CS.RESOURCE.AUTOBOXING

Auto-boxing inside a loop

This checker reports any instance of automatic conversion of a value type into a reference type object due to auto-boxing, whenever such conversion takes place inside a loop body. Auto-boxing is applied by the compiler in assignments or in the application of binary operations between value type constants or variables and reference type objects. Auto-boxing involves the allocation of memory on heap, and constructing the object, and thus can consume significant system resources. This can be especially impactful when such conversion takes place within loops.

Vulnerability and risk

Auto-boxing contributes to software performance degradation, influencing the amount of resources consumed, and can potentially lead to a decrease in software responsiveness or the complete exhaustion of the available resources.

Mitigation and prevention

To prevent these negative effects, auto-boxing should be avoided.

Vulnerable code example 1

Copy
  using System;
  namespace AutoUnBox
  {
    class AutoBox {
      public void Example1() {
              TestAutoBox count = new TestAutoBox();
        for (long i = 0; i < 10; i++) {
          count += 0x2A;                       // CS.RESOURCE.AUTOBOXING
        }
     }
   }
   class TestAutoBox {
 
     TestAutoBox(int intValue) {
       this.value1 = intValue;
     }
 
     private int value1 { set; get; }
 
     public static implicit operator TestAutoBox(int v) {
       return new TestAutoBox(v);
    }
   }
 }

Klocwork produces an issue report at line 8 indicating that ,“Autoboxing is applied at line 8 to the primitive type ‘int ‘that is automatically converted to 'count'.” In this case, autoboxing is done within the loop, converting a constant integer value to an object first, before the ‘+’ operation with the object variable count.

Fixed code example 1

Copy
  using System;
  namespace AutoUnBox
  {
    class AutoBox {
      public void Example1() {
              TestAutoBox count = new TestAutoBox();
        int countValue = 0;
        for (long i = 0; i < 10; i++) {
          countValue += 0x2A;                       // no CS.RESOURCE.AUTOBOXING
       }
       count = countValue;
     }
   }
   class TestAutoBox {
 
     TestAutoBox(int intValue) {
       this.value1 = intValue;
     }
 
     private int value1 { set; get; }

     public static implicit operator TestAutoBox(int v) {
       return new TestAutoBox(v);
     }
   }
 }

In the fixed code, both the operands at line 8 are built-in integers in the loop, so no issue is reported.