c# - string concatenation and reference equality -


in c# strings immutable , managed. in theory mean concatenation of strings a , b cause allocation of new buffer pretty obfuscated. when concatenate identity (the empty string) reference maintains intact. compile time optimization or overloaded assignment operator making decision not realloc @ runtime? furthermore, how runtime/compiler handle s2's value/allocation when modify value of s1? program indicate memory @ original address of s1 remains intact (and s2 continues pointing there) while relloc occurs new value , s1 pointed there, accurate description of happens under covers?

example program;

    static void main(string[] args)     {         string s1 = "some random text chose";         string s2 = s1;         string s3 = s2;          console.writeline(object.referenceequals(s1, s2)); // true          s1 = s1 + "";          console.writeline(object.referenceequals(s1, s2)); // true         console.writeline(s2);          s1 = s1 + " else";          console.writeline(object.referenceequals(s1, s2)); // false cause s1 got realloc'd         console.writeline(object.referenceequals(s2, s3));         console.writeline(s2);          console.readkey();     } 

when concatenate identity (the empty string) reference maintains intact. compile time optimization or overloaded assignment operator making decision not realloc @ runtime?

it both compile time optimization , optimization performed in implementation of overloaded concatenation operator. if concat 2 compile time literals, or concat string known null or empty @ compile time, concatenation done @ compile time, , potentially interned, , therefore reference equal other compile time literal string has same value.

additionally, string.concat implemented such if concat string either null or empty string, returns other string (unless other string null, in case returns empty string). test have demonstrates this, you're concatting non-compile time literal string empty string , it's staying reference equal.

of course if don't believe own test, can look @ source see if 1 of arguments null returns other.

if (isnullorempty(str0)) {     if (isnullorempty(str1)) {         return string.empty;     }     return str1; }  if (isnullorempty(str1)) {     return str0; } 

Popular posts from this blog