Barcode internment. How does the compiler know?

I know what string interning is and why the following code behaves like this:

var hello = "Hello"; var he_llo = "He" + "llo"; var b = ReferenceEquals(hello, he_llo); //true 

or

 var hello = "Hello"; var h_e_l_l_o = new string(new char[] { 'H', 'e', 'l', 'l', 'o' }); var b = ReferenceEquals(hello, he_llo); //false 

... or I thought I did, because because of this, I found a subtle error in some code, because of which I work:

 var s = ""; var sss = new string(new char[] { }); var b = ReferenceEquals(s, sss); //True!? 

How does the compiler know that sss will actually be an empty string?

+6
source share
1 answer

If an empty pool or an empty array is passed in the string constructor, it returns an empty string.

It is indicated in the comment in the reference code .

  // Creates a new string with the characters copied in from ptr. If // ptr is null, a 0-length string (like String.Empty) is returned. 

You can also see the same result with an null array, like:

 char[] tempArray = null; var s = ""; var sss2 = new string(tempArray); var b = ReferenceEquals(s, sss2); //True!? 
+4
source

Source: https://habr.com/ru/post/1014494/


All Articles