Pretending .NET strings are value type

后端 未结 4 1791
死守一世寂寞
死守一世寂寞 2021-02-09 11:45

In .NET, strings are immutable and are reference type variables. This often comes as a surprise to newer .NET developers who may mistake them for value type objects due to their

4条回答
  •  礼貌的吻别
    2021-02-09 12:41

    An immutable class acts like a value type in all common situations, and you can do quite a lot of programming without caring much about the difference.

    It's when you dig a little deeper and care about performance that you have real use for the distinction. For example to know that although passing a string as a parameter to a method acts as if a copy of the string is created, the copying doesn't actually take place. This might be a surprise for people used to languages where strings actually are value types (like VB6?), and passing a lot of strings as parameters would not be good for performance.

提交回复
热议问题