98-372 · Question #16
Which of the following sample code segments demonstrates unboxing?
The correct answer is A. object obj = 12345;. The following sample code segment demonstrates unboxing: object obj = 12345; int it = (int) obj; Unboxing is used to convert a reference type to a value type. In this sample code segment, the Integer object is a value type, and the instance of the Object class is a reference type
Question
Which of the following sample code segments demonstrates unboxing?
Options
- Aobject obj = 12345;
- Bdouble dou = 12345;
- Cint it = 12345;
- Dint it = 12345;
How the community answered
(40 responses)- A73% (29)
- B15% (6)
- C8% (3)
- D5% (2)
Explanation
The following sample code segment demonstrates unboxing: object obj = 12345; int it = (int) obj; Unboxing is used to convert a reference type to a value type. In this sample code segment, the Integer object is a value type, and the instance of the Object class is a reference type. Therefore, converting from the reference type to the value type needs unboxing. Unboxing is the inverse of boxing. Unboxing is used to explicitly convert reference type to value type. An unboxing operation consists of the following two actions: - Checking the object instance to make sure it is a boxed value of the given value type. - Copying the value from the instance into the value type variable. The following statements will demonstrate an unboxing operation: int test=457; //A value type object obj=test; //A reference type int result=(int) obj; //Unboxing The unboxing conversion to a given value will succeed at runtime. This is possible only if the source argument is a reference to an object that is compatible and not null. Otherwise, an InvalidCastException is thrown. Answer: B and D are incorrect. Converting between two value types requires neither boxing nor Answer: C is incorrect. Converting a value type to a reference type is called boxing.
Topics
Community Discussion
No community discussion yet for this question.