Is string actually an array of chars or does it just have an indexer?

后端 未结 12 1823
無奈伤痛
無奈伤痛 2020-12-06 09:58

As the following code is possible in C#, I am intersted whether string is actually an array of chars:

string a=\"TEST\";
char C=a[0]; // will be T

12条回答
  •  眼角桃花
    2020-12-06 10:07

    A string object contains a continuous block of characers, just like an array of characters, but the string object neither is, nor contains an array object.

    The compiler knows that the string string is immutable, so it can do certain optimisations when you access a string, in the same manner that it does optimisations when you access an array. So, when you access a string by index, it's likely that the code ends up accessing the string data directly rather than calling an indexer property.

提交回复
热议问题