C#.NET — Behavior of a struct variable: location, constructors, GC, and inheritance. Given: struct Book { private string name; private int noofpages; private float price; } Book b = new Book(); Which statement is correct?
-
AThe structure variable b will be created on the heap.
-
BWe can add a zero-argument constructor to the above structure.
-
CWhen the program terminates, variable b will get garbage collected.
-
DThe structure variable b will be created on the stack.
-
EWe can inherit a new structure from struct Book.
Answer
Correct Answer: The structure variable b will be created on the stack.
Explanation
Introduction / Context:This question checks core facts about structs: storage location for locals, constructors, garbage collection, and inheritance rules. It uses a simple struct Book and a local variable b to probe your understanding of value-type semantics in C#.
Given Data / Assumptions:
- Book is a struct; b is declared locally (typical example in Main).
- No explicit constructors are shown.
Concept / Approach:Structs are value types. A local variable of a value type is typically allocated on the stack. The struct data is not garbage collected as a separate heap object; instead, it is cleaned up when the stack frame unwinds. Parameterless constructors for structs were historically not user-definable and a parameterless default is provided by the runtime; inheritance between structs is not allowed (besides implicit derivation from System.ValueType).
Step-by-Step Solution:
Evaluate storage: local value-type variable → stack. GC behavior: garbage collection concerns heap objects; a local value-type variable itself is not a separately collected object. Constructors: in classic C#, user-defined parameterless constructors in structs were disallowed; initialization uses new Book(). Inheritance: you cannot derive one struct from another; structs can implement interfaces only.Verification / Alternative check:Boxing Book to object (object o = b) creates a heap object; unboxed value types again reside inline where used. Attempting “struct Derived : Book {}” fails to compile.
Why Other Options Are Wrong:
- A: Describes heap allocation; not true for a local value-type variable.
- B: Parameterless user-defined constructors are not the standard rule tested here.
- C: GC collects heap objects, not stack-allocated value variables like b.
- E: Struct inheritance (besides ValueType) is not supported.
Common Pitfalls:Confusing value vs reference semantics, and assuming GC applies to all variables equally.
Final Answer:The structure variable b will be created on the stack.