Boxing, unboxing, and nullability in C#.NET — identify the correct statements. 1) We can assign values of any type to variables of type object. 2) Converting a value type to object is called unboxing. 3) Converting an object back to a value type is called boxing. 4) A Boolean variable cannot have a value of null (without Nullable). 5) When a value type is boxed, a new object must be allocated and constructed on the managed heap.
-
A1, 4, 5
-
B1, 5
-
C3, 4
-
D2, 3
-
E1, 2
Answer
Correct Answer: 1, 4, 5
Explanation
Introduction / Context:Boxing and unboxing are core CLR mechanisms that allow value types to be treated as objects. This question also touches on nullability of primitive value types like bool.
Given Data / Assumptions:
- object can reference any managed type.
- Value types (int, bool, struct) differ from reference types in storage and behavior.
- Nullable
(or T?) is not implied unless stated.
Concept / Approach:Boxing is the conversion of a value type instance to a reference type (object), which allocates a new object on the managed heap and copies the value. Unboxing is the reverse: extracting the value type from an object reference, requiring a cast. A non-nullable bool cannot be null; only bool? can. Because object is the ultimate base type for all managed types, an object variable can hold a reference to any type instance.
Step-by-Step Solution:
(1) True — object references can point to any type (after boxing for value types).(2) False — that is the definition of boxing, not unboxing.(3) False — unboxing converts object → value type.(4) True — bool cannot be null unless declared as NullableVerification / Alternative check:Write a snippet: int x = 5; object o = x; int y = (int)o; Observe the boxing (x → o) and unboxing (o → y).
Why Other Options Are Wrong:Options that include statements 2 or 3 invert the definitions of boxing and unboxing.
Common Pitfalls:Confusing the direction of boxing/unboxing; overlooking that non-nullable primitives cannot hold null.
Final Answer:1, 4, 5