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,

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.