Why string.Replace(“X”,“Y”) works only when assign

2020-04-05 07:57发布

I guess it has to do something with string being a reference type but I dont get why simply string.Replace("X","Y") does not work?

Why do I need to do string A = stringB.Replace("X","Y")? I thought it is just a method to be done on specified instance.

EDIT: Thank you so far. I extend my question: Why does b+="FFF" work but b.Replace does not?

标签: c# string
11条回答
何必那么认真
2楼-- · 2020-04-05 08:19

String.Replace is a shared function of string class that returns a new string. It is not an operator on the current object. b.Replace("a","b") would be similar to a line that only has c+1. So just like c=c+1 actually sets the value of c+1 to c, b=b.Replace("a","b") sets the new string returned to b.

查看更多
三岁会撩人
3楼-- · 2020-04-05 08:22

As everyone above had said, strings are immutable.

This means that when you do your replace, you get a new string, rather than changing the existing string.

If you don't store this new string in a variable (such as in the variable that it was declared as) your new string won't be saved anywhere.

查看更多
一纸荒年 Trace。
4楼-- · 2020-04-05 08:22

Just to be more explicit. string.Replace("X","Y") returns a new string...but since you are not assigning the new string to anything the new string is lost.

查看更多
男人必须洒脱
5楼-- · 2020-04-05 08:24

Why doesn't stringA.Replace("X","Y") work?
Why do I need to do stringB = stringA.Replace("X","Y"); ?

Because strings are immutable in .NET. You cannot change the value of an existing string object, you can only create new strings. string.Replace creates a new string which you can then assign to something if you wish to keep a reference to it. From the documentation:

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

Emphasis mine.


So if strings are immutable, why does b += "FFF"; work?

Good question.

First note that b += "FFF"; is equivalent to b = b + "FFF"; (except that b is only evaluated once).

The expression b + "FFF" creates a new string with the correct result without modifying the old string. The reference to the new string is then assigned to b replacing the reference to the old string. If there are no other references to the old string then it will become eligible for garbage collection.

查看更多
戒情不戒烟
6楼-- · 2020-04-05 08:28

A StringBuilder supports the inline Replace method.

Use the StringBuilder if you need to do a lot of string manipulation.

查看更多
▲ chillily
7楼-- · 2020-04-05 08:29

Strings are immutable. Any operation changing them has to create a new string.

查看更多
登录 后发表回答