C#.NET — When does a struct variable get destroyed (become eligible for reuse)?

Difficulty: Easy

Correct Answer: When it goes out of scope.

Explanation:


Introduction / Context:
Structs are value types. Their lifetime semantics differ from reference types managed by the garbage collector.



Given Data / Assumptions:

  • We consider a local struct variable in typical code.
  • We contrast GC-based lifetime (for objects) with scope-based lifetime (for values).


Concept / Approach:
A struct variable's storage is typically reclaimed when it goes out of scope (for locals, at the end of the method or block). The GC does not “collect” standalone stack values. If a struct is a field within a reference type, its lifetime follows that containing object. The presence or absence of new only affects initialization, not fundamental lifetime.



Step-by-Step Solution:

Recognize struct = value type → usually stack/inlined storage.Scope ends → storage is eligible for reuse; no GC step needed for the value itself.Contrast: reference types are eligible for GC when unreachable, not at scope exit.


Verification / Alternative check:
Inspect generated IL and JIT behavior; locals are allocated in the stack frame and discarded on method exit.



Why Other Options Are Wrong:

  • A: GC is for reference types, not for simple value locals.
  • B: new vs no-new does not change lifetime.
  • D/E: Irrelevant to .NET managed lifetime; free()/delete() are not used in C#.


Common Pitfalls:
Assuming structs behave like heap objects with GC; they usually do not.



Final Answer:
When it goes out of scope.

More Questions from Structures

Discussion & Comments

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