C#.NET — Trace pass-by-value vs pass-by-reference (ref) and predict the print sequence. Program: namespace CuriousTabConsoleApplication { class SampleProgram { static void Main(string[] args) { int num = 1; funcv(num); Console.Write(num + ", "); funcr(ref num); Console.Write(num + ", "); } static void funcv(int num) { num = num + 10; Console.Write(num + ", "); } static void funcr(ref int num) { num = num + 10; Console.Write(num + ", "); } } } What will be printed?

Difficulty: Medium

Correct Answer: 11, 1, 11, 11,

Explanation:


Introduction / Context:
This question contrasts pass-by-value with pass-by-reference (ref) in C#, asking you to follow state changes of a variable across method calls and output statements.


Given Data / Assumptions:

  • num starts at 1.
  • funcv(int num) uses pass-by-value.
  • funcr(ref int num) uses pass-by-reference.
  • Console.Write prints intermediate values with ", ".


Concept / Approach:
With pass-by-value, the callee receives a copy, so assignments inside do not affect the caller. With ref, the callee manipulates the caller’s variable directly. Carefully interleave the writes from inside the methods with writes in Main.


Step-by-Step Solution:

Call funcv(num): local num becomes 11 and prints "11, ". Caller's num remains 1. Back in Main: print caller's num — "1, ". Call funcr(ref num): now caller's num becomes 11 and prints "11, " from inside funcr. Back in Main again: num is still 11, so print "11, ".


Verification / Alternative check:
Mentally simulate or add labels to the outputs to separate method vs Main. You will see the four prints: 11 (funcv), 1 (Main), 11 (funcr), 11 (Main).


Why Other Options Are Wrong:

  • A ignores the increments.
  • C implies pass-by-value also affects the caller — incorrect.
  • D/E add further increments that never occur in the sequence.


Common Pitfalls:
Assuming that changing a parameter inside any method always changes the caller; that only happens with ref/out or when mutating a reference type's instance state.


Final Answer:
11, 1, 11, 11,

Discussion & Comments

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