Take the following example:
string me = "Ibraheem";
string copy = me;
me = "Empty";
Console.WriteLine(me);
Console.WriteLine(copy);
The output is:
Empty
Ibraheem
Since it is class type (i.e. not a struct), String copy should also contain Empty because the = operator in C# assigns reference of objects rather than the object itself (as in C++)??
System.Stringis not a value type. It exhibits some behaviors that are similar to value types, but the behavior you have come across is not one of them. Consider the following code.If you checked the output of
foo.SomeProperty, do you expect it to be the same assomeOtherFoo.SomeProperty? If so, you have a flawed understanding of the language.In your example, you have assigned a string a value. That’s it. It has nothing to do with value types, reference types, classes or structs. It’s simple assignment, and it’s true whether you’re talking about strings, longs, or Foos. Your variables temporarily contained the same value (a reference to the string “Ibraheem”), but then you reassigned one of them. Those variables were not inextricably linked for all time, they just held something temporarily in common.