Unboxing explicitly converts an object that was converted to an object type by boxing back to a value type. Unboxing operations allow objects to be treated as value types by performing implicit conversion from the object type. Most applications perform a large number of unboxing operations that you cannot avoid. For instance, unboxing is performed automatically every time that you need to change an object to a primitive value type (such as integers, strings, etc.). Although this negatively impacts performance, there is no way to avoid it.
If the code is declaring the unboxed value itself, you can generally eliminate the unboxing to enhance application performance. For instance, the code may convert an object to a user-created value type (a structure) in order to avoid the performance hits associated with using an object. If unboxing is performed on the value, however, the performance advantages of using a value type are outweighed by the disadvantages of unboxing.
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 = ("10, 10")
p1 = CType(o, point)
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 Class1
{
static void BoxingTest()
{
object o;
o = ("1, 2");
point p1;
p1 = (point) o; // Unboxing performed here!
}
}