Tech Off Post

Single Post Permalink

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

    I think what you are not considering is how memory in a modern computer works.

    When you ask the OS to give you some memory to store data (like a string) that space can be anywhere in the memory address space...

    So, let's assume you asked the OS to store a 10 character string (10 * 2 bytes = 20 bytes), so you have your 20 bytes and you place your String data in there.

    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.

    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.