int number = 10;Unboxing is not type safe. It requires a cast because the compiler cannot determine the type of the object. If the object is not the correct type, it will cause an exception during the cast operation.
// The following causes a box operation
// numRef will refer to an object on the
// heap which contains a copy of number (10)
object numRef = number;
// Next unbox the value by casting it to
// the appropriate type
int numberB = (int) numRef;
Large numbers of boxing and unboxing operations can become a performance problem. It should be avoided if possible. In particular, Generic types do not depend on boxing operations and they should be used whenever possible. Also, generic types maintain type safety.
0 Comments