Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

c# - Why string.Replace("X","Y") works only when assigned to new string?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...