A simple question regarding String
-
Hi, i'm confused. If String is a reference type, why b does not change if a is modified, since b is just referring to a? E.g.
String a = "Hello";
String b = a;a = a.ToUpper();
Console.WriteLine(a);
Console.WriteLine(b);HELLO
helloThanks
uus831 wrote:
If String is a reference type, why b does not change if a is modified, since b is just referring to a?
You're not passing a reference to a string, but invoking a method on such a reference, and putting the result back in
a
. The documentation[^] says that this method returns a copy of the string;' Returns a copy of this String converted to uppercase.
The method
ToUpper
is executed, and it returns a reference to a new string. This pointer is then stored in your A-variable, not touching B.I are Troll :suss:
-
Hi, i'm confused. If String is a reference type, why b does not change if a is modified, since b is just referring to a? E.g.
String a = "Hello";
String b = a;a = a.ToUpper();
Console.WriteLine(a);
Console.WriteLine(b);HELLO
helloThanks
-
Because it's not
a.ToUpper()
buta = a.ToUpper()
-ToUpper
doesn't change anything, it returns a new string. If you change the actual string (yes you can, unsafe code), b should probably change -
uus831 wrote:
If String is a reference type, why b does not change if a is modified, since b is just referring to a?
You're not passing a reference to a string, but invoking a method on such a reference, and putting the result back in
a
. The documentation[^] says that this method returns a copy of the string;' Returns a copy of this String converted to uppercase.
The method
ToUpper
is executed, and it returns a reference to a new string. This pointer is then stored in your A-variable, not touching B.I are Troll :suss:
Yes, Microsoft purposely made the
String
type act like a value type, even though it is really a reference type; it is immutable. Any operations on aString
produce a copy, or a partial copy, of the String; the underlying string data cannot be directly changed. This is why you have to doa = a.ToUpper();
in the first place, rather than theToUpper()
method directly changing theString
. This is also the reason that theStringBuilder
class exists, because it allows string manipulation without the extra copying, and thus has better performance in situations where lots of string manipulation will be happening.