Predict the output (parameter shadowing): namespace CuriousTabConsoleApplication { class Sample { int i; Single j; public void SetData(int i, Single j) { i = i; j = j; } public void Display() { Console.WriteLine(i + " " + j); } } class MyProgram { static void Main(string[] args) { Sample s1 = new Sample(); s1.SetData(10, 5.4f); s1.Display(); } } }

Difficulty: Easy

Correct Answer: 0 0

Explanation:


Introduction / Context:
This program demonstrates parameter shadowing of instance fields by method parameters with identical names. Without qualifying with this, assignments affect only parameters, not fields, leading to unchanged instance state.



Given Data / Assumptions:

  • Fields: i (int), j (Single) default to 0.
  • Method parameters: int i, Single j shadow the fields.
  • SetData assigns i = i and j = j without this.


Concept / Approach:
Inside SetData, the identifiers i and j refer to the parameters, not the fields. Therefore, i = i and j = j are self-assignments on the parameters. To assign to fields, you must write this.i = i; and this.j = j;



Step-by-Step Solution:

Initial field values: i = 0, j = 0.0f.Call SetData(10, 5.4f) → parameters receive values 10 and 5.4f.Assignments affect parameters only; fields remain 0 and 0.0f.Display prints the fields → “0 0”.


Verification / Alternative check:
Modify SetData to use this.i and this.j, re-run, and observe “10 5.4”.



Why Other Options Are Wrong:
They assume the fields changed, which they did not due to shadowing.



Common Pitfalls:
Naming parameters the same as fields without using this; misunderstanding variable scope.



Final Answer:
0 0

More Questions from Classes and Objects

Discussion & Comments

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