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

1  using System;
2  namespace AutoUnBox
3  {
4    class AutoBox {
5      public void Example1() {
6              TestAutoBox count = new TestAutoBox();
7        for (long i = 0; i < 10; i++) {
8          count += 0x2A;                       // CS.RESOURCE.AUTOBOXING
9        }
10     }
11   }
12   class TestAutoBox {
13 
14     TestAutoBox(int intValue) {
15       this.value1 = intValue;
16     }
17 
18     private int value1 { set; get; }
19 
20     public static implicit operator TestAutoBox(int v) {
21       return new TestAutoBox(v);
22    }
23   }
24 }

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

1  using System;
2  namespace AutoUnBox
3  {
4    class AutoBox {
5      public void Example1() {
6              TestAutoBox count = new TestAutoBox();
7        int countValue = 0;
8        for (long i = 0; i < 10; i++) {
9          countValue += 0x2A;                       // no CS.RESOURCE.AUTOBOXING
10       }
11       count = countValue;
12     }
13   }
14   class TestAutoBox {
15 
16     TestAutoBox(int intValue) {
17       this.value1 = intValue;
18     }
19 
20     private int value1 { set; get; }
21
22     public static implicit operator TestAutoBox(int v) {
23       return new TestAutoBox(v);
24     }
25   }
26 }

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