Search code examples
c#reference-type

C# How to get reference type behaviour with String?


This 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.


Solution

  • You can't. Strings are immutable.. which means you can't change them directly. Any changes to a string are actually a new string being returned.

    Therefore, this (which I assume you mean):

    string one = "Hello";
    string two = one;
    
    two = "World";
    
    Console.WriteLine(one);
    

    ..will print "Hello", because two is now an entirely new string and one remains as it was.