I have this doubt related to C# "String" reference types .
The following code:
string s = "lana del rey"
string d = s;
s = "elvis presley";
Console.Writeline(d);
Why the Output is not "elvis presley" ? If d is pointing to the same memory location of s ?
Could you please explain this?
A more detailed explanation of my initial question:
All your answers were very useful. That question came to me with this common code sample frecuently used to explain difference between value types and reference types:
class Rectangle
{
public double Length { get; set; }
}
struct Point
{
public double X, Y;
}
Point p1 = new Point();
p1.X = 10;
p1.Y = 20;
Point p2 = p1;
p2.X = 100;
Console.WriteLine(“p1.X = {0}”, p1.X);
Rectangle rect1 = new Rectangle
{ Length = 10.0, Width = 20.0 };
Rectangle rect2 = rect1;
rect2.Length = 100.0;
Console.WriteLine(“rect1.Length = {0}”,rect1.Length);
In this case, the second Console.WriteLine statement will output: “rect1.Length = 100”
In this case class is reference type, struct is value type. How can I demostrate the same reference type behaviour using a string ?
Thanks in advance.
It has nothing to do with mutability
string s = "lana del rey"
string d = s;
Here 2 variables s
and d
refer to the same object in memory.
s = "elvis presley";
here in the right part of the statement the new object is allocated and initialized with "elvis presley"
and assigned to s
. So now s
refers to another object. And while we haven't change the d
reference value - it continues referring to the "lana del rey"
as it originally did.
Now the real life analogy:
There are 2 people (A
and B
) pointing using their fingers to a building far away. They are independent to each other, and don't even see what another is pointing to. Then A
decides to start pointing to another building. As long as they aren't connected to each other - now A
points to another building, and B
continues pointing to the original building (since no one asked them to stop doing that)
PS: what you probably are confusing is the concept behind a pointer and a reference. Not sure if it makes sense to explain it here since you might be confused even more. But now at least you might google for the corresponding keywords.