Why don't we use new operator while initializing a string?

前端 未结 7 901
太阳男子
太阳男子 2020-12-13 06:05

I was asked this question in an interview: Is string a reference type or a value type.

I said its a reference type. Then he asked me why don\'t we use new operator

相关标签:
7条回答
  • 2020-12-13 07:12

    Here's my take, I'm not entirely sure, so take my answer with a grain of salt.

    String literals in .NET are self-contained, its length or other data structure is internally included in literal value itself. So, unlike C, assigning string literal in .NET is just a matter of assigning the memory address of whole data structure of string. In C, we need to use new in string class as it need to allocate other data structures around null-terminated string, length for instance.

    0 讨论(0)
提交回复
热议问题