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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With