Does String.Replace() create a new string if there's nothing to replace?

两盒软妹~` 提交于 2019-12-04 22:53:55

It does not return a new instance if there is nothing to replace:

string text1 = "hello world", text2 = text1.Replace("foo", "bar");
bool referenceEqual = object.ReferenceEquals(text1, text2);

After that code executes, referenceEqual is set to true.

Even better, this behavior is documented:

If oldValue is not found in the current instance, the method returns the current instance unchanged.

Otherwise, this would be implementation-dependent and could change in the future.

Note that there is a similar, documented optimization for calling Substring(0) on a string value:

If startIndex is equal to zero, the method returns the original string unchanged

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