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?

24th Jul 2021, 8:10 AM
a SnowFlake
a SnowFlake - avatar
4 odpowiedzi
+ 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.
24th Jul 2021, 8:50 AM
Abhay
Abhay - avatar
+ 2
Self answered question! 😯 BTW you need, whole boiler plate of C# to make it correct 😁
24th Jul 2021, 8:43 AM
Abhiyantā
Abhiyantā - avatar
0
S1 was never reassigned , it remained the same
24th Jul 2021, 8:20 AM
Saphal Poudyal
Saphal Poudyal - avatar
0
Ćheyat , string, like a classes, reference type. And If second variable gets a reference, then both these variables can change inner value.
24th Jul 2021, 8:23 AM
a SnowFlake
a SnowFlake - avatar