C#.NET — What happens when assigning one struct to another? Given: struct Address { private int plotno; private string city; } Address a = new Address(); Address b; b = a; Choose the correct effect of “b = a;”.

Difficulty: Easy

Correct Answer: All elements of a will get copied into corresponding elements of b.

Explanation:


Introduction / Context:
This question focuses on assignment semantics for structs (value types). Unlike reference types where assignment copies a reference, assigning one struct variable to another performs a field-by-field copy of the data (memberwise copy).


Given Data / Assumptions:

  • Address is a struct with two fields.
  • Two variables a and b exist; the statement b = a is executed.


Concept / Approach:
Struct assignment in C# duplicates the value content. After b = a, b contains its own independent copy of the fields that a had at the time of assignment. Future changes to a do not affect b, and vice versa. This contrasts with class (reference type) variables, where b = a would make both references point to the same object.


Step-by-Step Solution:

Identify type category: Address is a struct → value type. Apply value-type assignment rule: b receives a memberwise copy of a. Result: b’s fields (plotno, city) become equal to a’s fields at copy time; they are now independent values.


Verification / Alternative check:
Modify a.plotno after assignment; observe that b.plotno remains unchanged, confirming copy-by-value semantics for structs.


Why Other Options Are Wrong:

  • B/E: Talk about copying an “address” or pointer; not applicable to value-type assignment.
  • C/D: Scope and garbage collection are unrelated to this assignment. a remains in scope until its block ends; structs are not heap objects requiring GC by default.


Common Pitfalls:
Projecting reference-type behavior onto structs or assuming pointer-like copying takes place.


Final Answer:
All elements of a will get copied into corresponding elements of b.

More Questions from Structures

Discussion & Comments

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