Posts Tagged ‘string’

string objects are immutable in C#

Posted: August 2, 2012 in C#, Uncategorized
Tags: ,

All string objects are immutable in C#. Objects of the class string, once created, can never represent any value other than the one they were constructed with. All operations that seem to “change” a string instead produce a new one. This is inefficient with memory, but extremely useful with regard to being able to trust that a string won’t change out form under you- because as long as you don’t change your reference, the string being referred to will never change.

A mutable object, by contrast, has data fields that can be altered. One or more of its methods will change the contents of the object, or it has a Property that, when written into, will change the value of the object.

If you have a mutable object- the most similar one to String is StringBuffer- then you have to make a copy of it if you want to be absolutely sure it won’t change out from under you. This is why mutable objects are dangerous to use as keys into any form of Dictionary or set- the objects themselves could change, and the data structure would have no way of knowing, leading to corrupt data that would, eventually, crash your program.

However, you can change its contents- so it’s much, much more memory efficient than making a complete copy because you wanted to change a single character, or something similar.

Generally, the right thing to do is use mutable objects while you’re creating something, and immutable objects once you’re done. This applies to objects that have immutable forms, of course; most of the collections don’t. It’s often useful to provide read-only forms of collections, though, which is the equivalent of immutable, when sending the internal state of your collection to other contexts- otherwise, something could take that return value, do something to it, and corrupt your data.

Just Trying To Explain string Concept 🙂

Hope This Post Will Help you Somehow . . :) . Feel Free To Ask Anything You Need.

Waiting For Your Valuable Feedback.