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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Munesh SharmaPosted May 21, 2014, 12:41 AM
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.