C#.NET — What will be the output of the following program (note value-type copy semantics for struct)? namespace CuriousTabConsoleApplication { struct Sample { public int i; } class MyProgram { static void Main() { Sample x = new Sample(); x.i = 10; fun(x); Console.Write(x.i + " "); } static void fun(Sample y) { y.i = 20; Console.Write(y.i + " "); } } }

Difficulty: Medium

Correct Answer: 20 10

Explanation:


Introduction / Context:
Structs are value types in C#. Passing them by value creates a copy. Modifying the copy inside a method does not affect the original variable in the caller.



Given Data / Assumptions:

  • struct Sample has a single public int field i.
  • Main initializes x.i = 10, calls fun(x), then prints x.i.
  • fun receives its parameter y by value and sets y.i = 20, then prints y.i.


Concept / Approach:
Because y is a by-value copy of x, changes to y.i do not propagate back to x. Therefore, fun prints 20, and after returning, Main still sees x.i = 10.



Step-by-Step Solution:

Inside fun: y is a copy → set y.i = 20 → Console.Write prints 20 and a space.Back in Main: x.i remains 10 → Console.Write prints 10 and a space.Combined output: "20 10".


Verification / Alternative check:
Change the method signature to static void fun(ref Sample y) and observe the different result (would print "20 20").



Why Other Options Are Wrong:

  • 10 20 / 10 10 / 20 20: Each assumes either no change or a reference-like update to x; not the case with by-value passing.
  • None of the above: Incorrect because "20 10" is achievable and correct.


Common Pitfalls:
Forgetting the distinction between structs (value types) and classes (reference types) when passing to methods.



Final Answer:
20 10

More Questions from Structures

Discussion & Comments

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