Why string is immutable in c#?
Why string is immutable in c#? any Why StringBuilder is mutable? Please let me know internal working of it.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Munesh SharmaRank #174 · 13.9K reputationPosted May 20, 2014, 8:41 PM EDT
outorref(since that changes the reference, not the object). A programmer therefore knows that ifstring x = "abc"at the start of a method, and that doesn't change in the body of the method, thenx == "abc"at the end of the method."abc" == "ab" + "c". While this doesn't require immutability, the fact that a reference to such a string will always equal "abc" throughout its lifetime (which does require immutability) makes uses as keys where maintaining equality to previous values is vital, much easier to ensure correctness of (strings are indeed commonly used as keys).Christmas.AddMonths(1)produces a newDateTimerather than changing a mutable one. (Another example, if I as a mutable object change my name, what has changed is which name I am using, "Jon" remains immutable and other Jons will be unaffected.return this. Since the copy can't be changed anyway, pretending something is its own copy is safe.