0
I can't yo ask a question.
static void Main() { string s1 = "Hi"; string s2 = s1; s2 = "Hey"; WriteLine (s1 + s2) //HiHey } Why this code output "HiHey", but not "HeyHey". String is reference type and don't copies a value?
4 Answers
+ 3
It looks like since string is a immutable type, assigning s2 with value "Hey" creates a new object as is evident by the following piece of code.
string s1 = "Hi";
string s2 = s1;
int a=s1.GetHashCode();
int b=s2.GetHashCode();
Console.WriteLine(a);
Console.WriteLine(b);
s2 = "Hey";
a=s2.GetHashCode();
Console.WriteLine(s1 + s2);
Console.WriteLine(a);
}
Take a look at section " immutability of string" In the following article.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/
Edit: about them being reference type, i don't have an answer for it .But might be true since you can see the hashcodes are same when s1 is assigned to s2 but also they are immutable so assigning new value creates a new object.
+ 2
Self answered question! đŻ
BTW you need, whole boiler plate of C# to make it correct đ
0
S1 was never reassigned , it remained the same
0
Äheyat , string, like a classes, reference type. And If second variable gets a reference, then both these variables can change inner value.