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

后端 未结 12 2495
抹茶落季
抹茶落季 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:52

    It is not a value type because performance (space and time!) would be terrible if it were a value type and its value had to be copied every time it were passed to and returned from methods, etc.

    It has value semantics to keep the world sane. Can you imagine how difficult it would be to code if

    string s = "hello";
    string t = "hello";
    bool b = (s == t);
    

    set b to be false? Imagine how difficult coding just about any application would be.

提交回复
热议问题