CS.BOXING

Avoid boxing/unboxing when possible.

When a value type is used in a place where an object reference is expected, the value type is automatically converted into a an object by placing it in a "box". At the least, this is often not efficient.

Vulnerability and risk

When boxed objects are used in collections, there can be unexpected behavior. Further, boxing occurs automatically and so one may not realize that it was introduced. It is always worth checking to see if boxing was the intended behavior.

Vulnerable code example

Copy
  using System.Collections;
  public struct MyData
  {
      int _data;
      public MyData(int data)
      {
         _data = data;
      }
      public void setData(int newData)
     {
         _data = newData;
     }
 }
 public class Worker
 {
     public static void work()
     {
         ArrayList datasCollection = new ArrayList();
         MyData data = new MyData(0);
         datasCollection.Add(data); //boxing - rule violation
         //.....
         MyData currentData = (MyData)datasCollection[0]; //unboxing - rule violation
         currentData.setData(1);
     }
 }

Fixed code example

Copy
  // Fix #1
  using System.Collections;
  public class MyData
  {
      int _data;
      public MyData(int data)
      {
          _data = data;
      }
     public void setData(int newData)
     {
         _data = newData;
     }
 }
 public class Worker
 {
     public static void work()
     {
         ArrayList datasCollection = new ArrayList();
         MyData data = new MyData(0);
         datasCollection.Add(data);
         //.....
         MyData currentData = (MyData)datasCollection[0];
         currentData.setData(1);
     }
 }