C#.NET — Which statements about classes vs. structs are true? 1) A class is a reference type, whereas a struct is a value type. 2) Objects are created using new, whereas struct variables can be created using new or without new. 3) A struct variable will always be created slower than an object. 4) A struct variable will die when it goes out of scope. 5) An object will die when it goes out of scope.

Difficulty: Easy

Correct Answer: 1, 2, 4

Explanation:


Introduction / Context:
Classes and structs differ in allocation, lifetime, and semantics. Understanding these distinctions helps you choose the right type for performance and design.



Given Data / Assumptions:

  • Class → reference type (heap, managed by GC).
  • Struct → value type (typically stack or inlined within containing objects).
  • Scope and reachability affect lifetimes differently.


Concept / Approach:
1) Correct: class is reference type; struct is value type. 2) Correct: you can declare a struct variable without new (but you must assign all fields before use), or with new to run its constructor. 3) Incorrect: performance varies by scenario; no “always slower.” 4) Correct: a local struct value typically becomes eligible for reuse when its scope ends. 5) Incorrect: objects on the managed heap are reclaimed by GC based on reachability, not scope.



Step-by-Step Solution:

Validate 1: true by definition in C#.Validate 2: true; both forms are legal for structs.Validate 3: false; creation cost depends on context and size.Validate 4: true; value leaves scope and its storage is reclaimed/overwritten.Validate 5: false; GC timing is independent of lexical scope.


Verification / Alternative check:
Inspect IL or perform micro-benchmarks to observe stack vs heap behaviors and GC timing.



Why Other Options Are Wrong:

  • 3, 5 and 3, 4, 5: Include false statements 3 and 5.
  • 2, 4: Omits true statement 1.
  • None of these: Incorrect because 1, 2, 4 are correct.


Common Pitfalls:
Assuming GC collects objects exactly at scope exit; it does not.



Final Answer:
1, 2, 4

More Questions from Structures

Discussion & Comments

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