C# Boxing and unboxing

  1. Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

    Consider the following declaration of a value-type variable:

    int i = 123;

    object o = i;

  1. Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:

    Checking the object instance to make sure that it is a boxed value of the given value type.

    Copying the value from the instance into the value-type variable.

  1. Is and as operator are used to safely type cast variables so that it does not throw exceptions. As operator is more efficient than is operator as AS returns the actual values if the cast is successful while is operator just returns Boolean values on testing cast conversions.

1 thought on “C# Boxing and unboxing”

Leave a Reply

Your email address will not be published. Required fields are marked *