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:29

To answer your extended question, b+="FFF" is equivalent to b = b + "FFF", so basically you are creating a new string here also.

查看更多
走好不送
3楼-- · 2020-04-05 08:32

Strings are immutable, which means that once they are created, they cannot be changed anymore. This has several reasons, as far as I know mainly for performance (how strings are represented in memory).

See also (among many):

As a direct consequence of that, each string operation creates a new string object. In particular, if you do things like

foreach (string msg in messages)
{
    totalMessage = totalMessage + message;
    totalMessage = totalMessage + "\n";
}

you actually create potentially dozens or hundreds of string objects. So, if you want to manipulate strings more sophisticatedly, follow GvS's hint and use the StringBuilder.

查看更多
ら.Afraid
4楼-- · 2020-04-05 08:35

Because strings are immutable. Any time you change a string .net creates creates a new string object. It's a property of the class.

Immutable objects
String Object

查看更多
啃猪蹄的小仙女
5楼-- · 2020-04-05 08:37

Yes its a method of System.String. But you can try a = a.Replace("X","Y");

查看更多
叼着烟拽天下
6楼-- · 2020-04-05 08:38

Why "b+="FFF"works but the b.replace is not

Because the += operator assigns the results back to the left hand operand, of course. It's just a short hand for b = b + "FFF";.

The simple fact is that you can't change any string in .Net. There are no instance methods for strings - you must always assign the results of an operating back to a string reference somewhere.

查看更多
登录 后发表回答