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?

Difficulty: Easy

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.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion