Strings vs classes when both are reference types

后端 未结 4 2044
北荒
北荒 2021-02-02 00:07

Here is how my last interview went:

Question: Where are strings stored?

Answer: Heap since it is a reference type

4条回答
  •  鱼传尺愫
    2021-02-02 01:00

    Strings are immutable because logically, they are a single value, and being mutable would lead to a lot of unexpected behavior.

    However, strings are not value types, because they tend to be passed around a lot, which would require a lot of copying of values. This would become quite expensive, especially for large strings.

    So in order to get the best of both worlds, strings in .Net are reference types, but also immutable.

提交回复
热议问题