Is it possible to replace a substring in a string without assigning a return value?
I have a string:
string test = "Hello [REPLACE] world";
<
You can't, because string
is immutable. It was designed so that any "changes" to a string would actually result in the creation of a new string
object. As such, if you don't assign the return value (which is the "updated" string, actually copy of the original string with applied changes), you have effectively discarded the changes you wanted to make.
If you wanted to make in-place changes, you could in theory work directly with a char[]
(array of characters), but that is dangerous, and should be avoided.
Another option (as pointed out by Mr. Skeet below) is to use StringBuilder
and its Replace()
method. That being said, simple replacements like the one you've shown are quite fast, so you may not want to bother with a StringBuilder
unless you'll be doing so quite often.