C
C#2y ago
Scartissue

❔ arent strings reference types?

string str1 = "string 1";
string str2 = "string 2";

str1 = str2;
str1 = "BLAHH";

Console.WriteLine(str1 + "\t" + str2);
Console.ReadKey();
string str1 = "string 1";
string str2 = "string 2";

str1 = str2;
str1 = "BLAHH";

Console.WriteLine(str1 + "\t" + str2);
Console.ReadKey();
why doesnt this print out BLAHH BLAHH
10 Replies
333fred
333fred2y ago
Strings are reference types. However, you are confusing what that means here str1 is a reference. When you reassign it, you're not changing other references to that same value You never changed what str2 is ("string 2"), so it never changes
Scartissue
ScartissueOP2y ago
string str1 = "string 1";
string str2 = "string 2";

str1 = str2;
str2 = "BLAHH";

Console.WriteLine(str1 + "\t" + str2);
Console.ReadKey();
string str1 = "string 1";
string str2 = "string 2";

str1 = str2;
str2 = "BLAHH";

Console.WriteLine(str1 + "\t" + str2);
Console.ReadKey();
what about this case str1 is pointing to str2 and str2 is changed to "BLAHH" but it doesnt change str1
Jimmacle
Jimmacle2y ago
you're misunderstanding str2 = "BLAHH" isn't changing the value of the string str2 references, it's changing the reference to an entirely new string. so the contents of the string that str1 references never changes C# strings are immutable
333fred
333fred2y ago
No. str1 is pointing to the same string that str2 is pointing to. Then, you reassign str2 to point to a new string. That doesn't affect what str1 is pointing to
Scartissue
ScartissueOP2y ago
ooh
Florian Voß
Florian Voß2y ago
this immutability is also why people often say string is a reference type that behaves like a value type. This is how I remember it
333fred
333fred2y ago
This has nothing to do with string immutability, and all reference types have exactly the same behavior as these examples
Jester
Jester2y ago
thats when youre comparing strings
Florian Voß
Florian Voß2y ago
right, sorry
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server