Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hi,
If String is a reference type, then why strOriginal1 is not changed from "Original String2" to "Original String3" ?
C#
string strOriginal1 = "Original String1";
 string strOriginal2 = "Original String2";

 strOriginal1 = strOriginal2;

 strOriginal2 = "Original String3";
Console.WriteLine("Value of strOriginal1 at call: {0}", strOriginal1);
Console.WriteLine( "Value of strOriginal2 at call: {0}", strOriginal2 );
Console.ReadLine();


Output:

Original String2
Original String3
Posted
Updated 21-Sep-11 20:39pm
v2

For immutable types (like strings are), the assignment operator copies content instead of creating another reference to the same object.
Therefore
C#
strOriginal1 = strOriginal2;
doesn't make strOriginal1 reference the same object as strOriginal2. Instead they stay separate objects which have identical values at the moment. Later changes to the latter don't affect the former.
 
Share this answer
 
Comments
Dalek Dave 22-Sep-11 3:43am    
Good Answer.
Strings are immutable objects in .net and their values are copied in the assignment statements.

In the statement
C#
strOriginal2 = "Original String3";

You are assigning strOriginal2 to a new reference which is pointing to the "Original String3" value.
 
Share this answer
 
v2
Comments
Dalek Dave 22-Sep-11 3:43am    
Good Call Mehdi.
Mehdi Gholam 22-Sep-11 4:06am    
Cheers!

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