-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

user3425420
  • 71
  • 1
  • 1
  • 3
  • Every time you change a string, a new string is made. You cannot alter an existing string, hence immutable. – Pete Garafano Sep 15 '14 at 17:03
  • `string s = "bob"; s[2] = 'a'` is not allowed. You cannot change a string. This is what is meant by "immutability". – BradleyDotNET Sep 15 '14 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. – Servy Sep 15 '14 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. – Pete Garafano Sep 15 '14 at 17:05
  • https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=c%23+immutable+string – B.K. Sep 15 '14 at 17:06
  • @PeteGarafano You're quite right it's semantics. Using corrects semantics are all the more important when someone doesn't understand the concepts being described. Saying that you can change an immutable object creates confusion, because the very definition of an object being immutable is that it cannot be changed. – Servy Sep 15 '14 at 17:07
  • @Servy - why ask the question "what else is there to understand" on one hand then acknowledge that it's quite possible someone doesn't understand the concepts being described on the other? I hate seeing weak comments like your first. The OP should've undoubtedly google'd this first, which is why he got my downvote, but you don't need to reply with smarmy sarcasm. –  Sep 15 '14 at 17:09

2 Answers2

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.

Godspark
  • 354
  • 2
  • 13
-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";
TechneWare
  • 263
  • 1
  • 7