Tech Off Post

Single Post Permalink

View Thread: Why are string types immutable in C#?
  • User profile image

    Manip wrote:
    Now the programmer thinks, let's place another character at the end of that 10 character string... So you ask the OS for another 2 bytes (a single character) but find that those two extra bytes are located at some generic and random location in memory.... Problem; you can't just have 10 characters at one place and the extra 1 at another... So to solve this each time you increase the size of a string the string is destroyed then the total length is requested from the memory pool.

    Basic also does this it is just transparent. Your strings *are* destroyed, you just don't have memory pointers in basic so don't notice.

    After seeing your reply and looking back over the original tutorial's code, I realized I misread part of the tutorial.  I think it was the way it was worded...

    [quote user ="This tutorial"]The reason for this behaviour is that string objects are 'immutable'. That is, the properties of these objects can't themselves change. So in order to change what a string variable references, a new string object must be created.[/quote]

    And, I wouldn't expect "s2" in the example above to take on the value of s1 when s1 changes.  Poor example, and a case of me trying to do too many things at once. Thanks for the replies, though!

    Good analogy by the way...

    Manip wrote:
    Here is an analogy to help (best I could think of).

    You and some friends go to the TicketMaster web-site to try and buy 5 tickets to the latest concert; you are given seat numbered 523, 524, 525, 526 and 527. Then another one of your friends suggests they want to come too... So you go to the TicketMaster website again in the hopes that you can buy seat 528 or 522 so you can all sit next to one another ... But the site won't let you pick where you want to sit. 

    Which leaves you two chooses. Either cancel all of your friend's seats and re-book all six or seat that last person somewhere else... But if you sat them somewhere else you might have trouble finding them after... So you decide to pick the first option and to cancel and re-book the full number.