Strings vs classes when both are reference types

落花浮王杯 提交于 2019-12-02 20:42:03

One of reasons strings were made immutable, even though they are reference types, was to make them look and behave like primitive types (e.g., int, double, float).

That's also the reason why strings are the only reference type that can be represented as a literal (e.g., "some string"). Lots of other languages take the same approach, like Java for example.

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.

The command one = ... sets the *pointer named one to a new value. Since two is a different pointer, it retains it's original value.

The command one.someString = ... modifies the object referred by one. two is still a different pointer, but since it points to the same object, the modifications are shared between them.

Strings share buffer. In your case if one and two were strings, they would be separate objects (two objects on the heap), but internally they would point to the same buffer (third object on the heap).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!