Posted: 10/1/2010
Hello Experts,
I'm a bit confused with the output which I'm getting in the below code.
class Test { public int i = 10; } class MyTestClass { public void Method() { int i = 99; var v = new Test(); v.i = 30; Another(v, i); Console.WriteLine(v.i); Console.WriteLine(i); } public void Another(Test v, int i) { i = 0; v.i = 20; v = new Test(); Console.WriteLine(v.i); Console.WriteLine(i); } public static void Main() { MyTestClass test = new MyTestClass(); test.Method(); Console.ReadLine(); } }//end class
I've 2 classes Test and MyTestClass. Now, the output which I'm getting here is 10 0 20 99. But according to me it should be 10 0 10 99. Because in the method "Another" we have instantiated Test class again. So at that time the value of v.i has become 10 which is fine. But when it returns to the Method() function. At that time the value is 20 . I'm wondering why it is 20 it should be 10.
Can anyone tell me why are we getting 20 instead of 10??
Thanks,
Sumit
Hmm.. Interesting.
Let me explain you .. When you called this method
Another(v, i);
You are passing the reference not the value and say the reference be x pointing to object y. Now when "Another" method is called upto this line
v.i = 20;
the same x pointer is pointing to y object and by executing this line now the value of i variable in y object becomes 20. Now when you execute this line
v = new Test();
Now the v which was having the pointer towards y object has been changed and it is now pointing to z , the old pointer is still referencing to y object . You have passed the "reference by value" so the original reference will remain intact when you come out of the called method and it will give you 20 as the value. GOT CONFUSED ? :) okay you will get your result if you pass it by "reference by reference" Here is the sample :
using System; class Test { public int i = 10; } class MyTestClass { public void Method() { int i = 99; var v = new Test(); v.i = 30; Another(ref v, i); Console.WriteLine(v.i); Console.WriteLine(i); } public void Another(ref Test v, int i) { i = 0; v.i = 20; v = new Test(); Console.WriteLine(v.i); Console.WriteLine(i); } public static void Main() { MyTestClass test = new MyTestClass(); test.Method(); Console.ReadLine(); } }//end class
10
0
99