3
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,

Oleks
  • 31,955
  • 11
  • 77
  • 132
Raghav55
  • 3,055
  • 6
  • 28
  • 38
  • Check this post will explain the things to you which you want [Why to use StringBuilder over string to get better performance](http://pranayamr.blogspot.com/2011/02/why-to-user-stringbuilder-over-string.html) – Pranay Rana Apr 27 '11 at 08:11

2 Answers2

5

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

Community
  • 1
  • 1
Aamir
  • 14,882
  • 6
  • 45
  • 69
  • This is wrong - `s` is definitely *not* pointed to the new string. The `Replace` method, along with many other string methods, creates a brand new string based on some logic, and returns this new string. `s` remains unchanged. The variable `m` is a reference to the new string. You need to replace `s` with `m` in your answer. – Graham Clark Apr 27 '11 at 08:22
2

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.

alex
  • 3,710
  • 32
  • 44