C#.NET — Understanding this and instance identity in method calls. Consider: namespace CuriousTabConsoleApplication { class Sample { int i, j; public void SetData(int ii, int jj) { this.i = ii; this.j = jj; } } class MyProgram { static void Main(string[] args) { Sample s1 = new Sample(); s1.SetData(10, 2); Sample s2 = new Sample(); s2.SetData(5, 10); } } } Which statement is correct?

Difficulty: Easy

Correct Answer: Contents of this will be different during each call to SetData().

Explanation:


Introduction / Context:
This item examines how the this reference represents the current instance and how parameter names can shadow field names. It also clarifies that you can use this explicitly to disambiguate fields from parameters.



Given Data / Assumptions:

  • Two instances: s1 and s2.
  • SetData uses parameters ii and jj and writes to fields i and j via this.
  • We corrected a missing semicolon to make the sample valid.


Concept / Approach:
this always refers to the instance on which the method is invoked. For s1.SetData(...), this is s1; for s2.SetData(...), this is s2. You do not pass this explicitly; the compiler and runtime supply it automatically.



Step-by-Step Solution:

Option (a): False — explicitly using this is allowed and common when disambiguating.Option (b): False — here parameters (ii, jj) differ from fields (i, j); this is not strictly required (i = ii; j = jj; also works), but using this is clear.Option (c): False — you never pass this manually in C# instance calls.Option (d): False — methods don’t “collect” this explicitly; it is implicit.Option (e): True — on s1 call, this is s1; on s2 call, this is s2.


Verification / Alternative check:
Log ReferenceEquals(this, s1) inside the first call and ReferenceEquals(this, s2) in the second; they evaluate to true respectively.



Why Other Options Are Wrong:
They misunderstand the role and lifetime of this or imply manual passing which C# does not require.



Common Pitfalls:
Thinking this must be passed or that it is constant across calls. It always points to the current receiver.



Final Answer:
Contents of this will be different during each call to SetData().

More Questions from Classes and Objects

Discussion & Comments

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