string s = "value_test_this";
string m = s.Replace('e','E');
StringBuilder strBuilder = new StringBuilder("value_test_this");
strBuilder.Replace('e','E');
since strings are immutable, how does the Replace
works in string class,
string s = "value_test_this";
string m = s.Replace('e','E');
StringBuilder strBuilder = new StringBuilder("value_test_this");
strBuilder.Replace('e','E');
since strings are immutable, how does the Replace
works in string class,
It creates another string in the memory and then points the m
to that new string. The old string also stays in the memory.
And that is exactly why StringBuilder
should be used if frequent modifications have to be made to the string.
If you want to know why Strings are immutable in C#, look at this SO discussion
If you do a string.Replace it's simply going to create a new string (since, as you said, it is immutable). In StringBuilder there's no new string being created, the one you have gets modified.