views:

328

answers:

11

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?

+22  A: 

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

Kevin
+1: This is definitive reason. However, I would say the real issue is the naming of the method. `Replace` implies the actual object would be manipulated.
James
+16  A: 

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.

Mark Byers
+1  A: 

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

Iraklis
+3  A: 

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

Josh Sterling
+6  A: 

Hi Petr.

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.

chiccodoro
+2  A: 

A StringBuilder supports the inline Replace method.

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

GvS
+2  A: 

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.

Joel Coehoorn
There are loads of instance methods on string! http://msdn.microsoft.com/en-us/library/system.string_methods(v=VS.100).aspxThey just never mutate their instance.
Donal Fellows
A: 

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.

Carlos
A: 

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

NimsDotNet
A: 

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.

The Real Diel
A: 

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.

Nat L
The underlying reason for this is because strings are immutable i.e. they can't be changed - See @Kevin answer. For me its a mistake on Microsofts part as the naming of the method is misleading.
James
What do you mean by a "String.Replace is a shared function" and "it is not an operator on the current object"?
Mark Byers
@James, Strings are immutable, but the variables aren't. The OP seems to want to know why the value of the variable isn't changed, but it's the poor naming convention that causes the problem, not the immutability of strings.@Mark, poor wording on my part. I meant to say it acts like a shared function, not that it is one. And like a reference type, it acts on the referenced string, not on the reference.
Nat L
@Nat: *"but the variables aren't"* a variable isn't a "type" in itself, all variables are of a certain type! Hence in the above example the variable is of type string (which is immutable). So I re-iterate, the reason the variable isn't changed is because **a string is immutable**.
James
@Nat: Also, the bad naming convention is only mis-leading to a developer, it has got nothing to do with *why* you can't change the string.
James
@James: The string variable is how we accsess some immutable string in memory. The first immutable string gets passed to the Replace function, and a new immutable string is returned. If you store the new string to the variable, the value of the variable has changed, but the two immutable strings are still in memory. The question isn't about how interned strings behave, it's about why not storing the returned value to the variable doesn't change the value of the variable.
Nat L
@Nat: yes I understand how variables work....the question was "why does string.replace only work when assigned to a new string" the answer to the question is simple, a string cannot be changed in .NET as it is immutable, therefore if you want to change a string variable you need to reassign the original one. As I already mentioned the confusion is the name of the function, but the cause of why is because strings are immutable and can't be changed...
James