Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference Between Assignment and Creating Instance of String in C#?

I have sample code.

var charMass = new char[] { 's', 't', 'r' };
string myString = new string(charMass);
string myString2 = new string(charMass);
string myString3 = "str";
string myString4 = "str";

bool bb1 = Object.ReferenceEquals(myString, myString2);
bool bb2 = Object.ReferenceEquals(myString, myString3);
bool bb3 = Object.ReferenceEquals(myString3, myString4);

Why bb1 and bb2 are false? I know that equals must show true, because it compares values, but what about memory allocation for those strings? Why myString3 and myString4 are pointing to the same block of memory in the heap but myString and myString2 not?

like image 690
Igor Lozovsky Avatar asked Dec 27 '22 08:12

Igor Lozovsky


1 Answers

C# compiler optimizes it so the same literals point to the same string instance

MSDN:

The intern pool conserves string storage. If you assign a literal string constant to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.

like image 159
sll Avatar answered Mar 15 '23 23:03

sll