C#.NET — What will be the output of this program (struct assignment copies the value)? namespace CuriousTabConsoleApplication { struct Sample { public int i; } class MyProgram { static void Main(string[] args) { Sample x = new Sample(); Sample y; x.i = 9; y = x; // copies the struct value y.i = 5; // modifies the copy Console.WriteLine(x.i + " " + y.i); } } }

Difficulty: Easy

Correct Answer: 9 5

Explanation:


Introduction / Context:
Assigning one struct variable to another copies the entire value. Subsequent changes to the target do not affect the source. This differs from class (reference type) assignment, which copies the reference.



Given Data / Assumptions:

  • x.i is set to 9.
  • y = x creates an independent copy.
  • Then y.i is changed to 5.


Concept / Approach:
Because Sample is a struct (value type), the assignment y = x duplicates the value in a new storage location. Changing y.i only changes that copy.



Step-by-Step Solution:

Initialize x.i = 9.Assign y = x → y.i becomes 9 in its own copy.Set y.i = 5 → only y changes; x remains 9.Print: x.i + " " + y.i → "9 5".


Verification / Alternative check:
Change Sample to a class and repeat; you would then see both values change via the shared reference.



Why Other Options Are Wrong:

  • 9 9: Would imply shared reference; not true for structs.
  • 5 5 or 5 9: Do not reflect independent copies with isolated changes.
  • None of the above: Incorrect because "9 5" is correct.


Common Pitfalls:
Expecting reference semantics with value types; always remember that structs copy by value.



Final Answer:
9 5

More Questions from Structures

Discussion & Comments

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