Total .NET Analyzer Rule Documentation  

Boxing Rule

Avoid Boxing to ensure optimal performance.

Remarks

Boxing allows value types to be treated as objects by performing an implicit conversion to the object type. Most applications perform a large number of boxing operations that you cannot avoid. For instance, boxing is performed automatically every time that you need to treat a primitive value type (such as integers, strings, etc.) as an object. Although this negatively impacts performance, there is no way to avoid it.

If the code is declaring the boxed value itself, you can generally eliminate the boxing to enhance application performance. For instance, the code may use a user-created value type (a structure) in order to avoid the performance hits associated with using an object. If boxing is performed on the value, however, the performance advantages of using a value type are outweighed by the disadvantages of boxing.


' VB
Structure point
Public x As Double
Public y As Double
Public Sub New(ByVal x As Double, ByVal y As Double)
Me.x = x
Me.y = y
End Sub
End Structure

Class PointClass
Sub Pt(ByVal x As String, ByVal y As String)
Dim p1 As New point()
Dim o As Object
p1.x = 10
p1.y = 10
o = p1 ' Boxing performed here!
End Sub
End Class

// C#
public struct point
{
public double x, y;
public point(double x, double y)
{
this.x = x;
this.y = y;
}
}

class PointClass
{
static void Pt()
{
object o;
point p1;
p1.x = 10;
p1.y = 10;
o = p1; // Boxing performed here.
}
}

Resolution

If the boxing operation is being performed on a value type that is declared within your code, remove the structure, and use an object type instead.

Note that if you are using a value type (struct) declared outside of your code (such as an integer, string, boolean, etc.) you generally cannot eliminate the boxing operation.

See Also

Boxing Conversion

Total .NET Analyzer Unboxing Rule

Performance Considerations