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

前端 未结 7 916
太阳男子
太阳男子 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.

提交回复
热议问题