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

前端 未结 7 920
太阳男子
太阳男子 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 06:46

    Strings are immutable reference types. There's the ldstr IL instruction which allows pushing a new object reference to a string literal. So when you write:

    string a = "abc";
    

    The compiler tests if the "abc" literal has already been defined in the metadata and if not declare it. Then it translates this code into the following IL instruction:

    ldstr "abc"
    

    Which basically makes the a local variable point to the string literal defined in the metadata.

    So I would say that your answer is not quite right as the compiler doesn't translate this into a call to a constructor.

提交回复
热议问题