In C#, why is String a reference type that behaves like a value type?

后端 未结 12 2341
抹茶落季
抹茶落季 2020-11-22 02:04

A String is a reference type even though it has most of the characteristics of a value type such as being immutable and having == overloaded to compare the text rather than

12条回答
  •  抹茶落季
    2020-11-22 02:43

    Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...

    (Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)

提交回复
热议问题