Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi all,

I have a class Test.
Test t1 = new Test();
Test t2 = new Test();
t2 = t1;
I know any change in t1 will affect t2. Please tell me what is the reason for that?
Posted
Comments
[no name] 23-Jun-11 2:50am    
what exactly you want to know. Please explain

The reason is quite simple: After t2=t1 both variables hold a reference to one and the same instance of class Test. The object created and assigned to t2 is no longer referenced anywhere and can garbage collected.

Cheers!

--MRB
 
Share this answer
 
v2
Comments
Silju MC 23-Jun-11 3:34am    
Thanks for your answer. I think this is the correct one.
Suppose the case of String. See bellow

String s1="Hello";
String s2="World";
s1=s2;

In this case, What happened in String pool??

Thanks in Advance
Manfred Rudolf Bihy 23-Jun-11 5:30am    
Strings are objects like very much everything in .net so the same applies as in your example. There is a slight difference though for strings. As they are immutable assigning a string literal twice to different variables will still produce only one instance. As all objects strings too can get garbage collected when they are no longer referenced.
Before assignment
t1 -----> Memory for t1
t2 -----> Memory for t2


When you assign t1 to t2, reference of t1 is passed to t2.
t1 -----> Memory for t1
t2 ---|


So, both the variables point to same object.
Change to any of them will be reflected in both.
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 23-Jun-11 4:11am    
Nice way to explain, my 5.
--SA
Prerak Patel 23-Jun-11 4:12am    
Thank you SA...
Silju MC 23-Jun-11 4:45am    
:-) Thanks
Prerak Patel 23-Jun-11 4:45am    
Welcome.
Silju MC 24-Jun-11 1:05am    
hiI really like your way of explanation... thank you once again and my 5... cheers... :-)
Because Object is of reference type. Which refer to the memory pointer.

When you assign t1 in t2. t2 and t1 hold the same pointer (memory address ref). and when we change t1 value t2 will automatically get changed.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900