-6

What is meant by "strings are immutable in c#". I need some examples to understand this.I can not find some proper examples to understand this

7
  • Every time you change a string, a new string is made. You cannot alter an existing string, hence immutable. Commented Sep 15, 2014 at 17:03
  • string s = "bob"; s[2] = 'a' is not allowed. You cannot change a string. This is what is meant by "immutability". Commented Sep 15, 2014 at 17:03
  • 1
    @PeteGarafano The whole point of immutability is that you can't change a string. It's not that you can change a string and doing so creates a new one. Commented Sep 15, 2014 at 17:03
  • @Servy its semantics in wording. Under the hood, the string never changes, the operation to "change" the string results in an entirely new string object being returned. For simplicity sake, it's a "new" string. Commented Sep 15, 2014 at 17:05
  • google.com/… Commented Sep 15, 2014 at 17:06

2 Answers 2

1

This means that if you assign

string s = "Hello";

you cannot modify the string s. Thus, if you do

s = "Goodbye";

the literal "Hello" is not modified, but a new literal "Goodbye" is assigned to s.

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

Comments

-2

Searching on your text "strings are immutable in c#" I find: http://msdn.microsoft.com/en-us/library/362314fe.aspx

Which seems to be saying that strings are never changed objects, they are always destroyed and re-created.

Per Microsoft:

Strings are immutable--the contents of a string object cannot be changed after the 
object is created, although the syntax makes it appear as if you can do this. 
For example, when you write this code, the compiler actually creates a new string object 
to hold the new sequence of characters, and that new object is assigned to b. The string "h" 
is then eligible for garbage collection.

string b = "h";
b += "ello";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.