Tech Off Post

Single Post Permalink

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

    Okay, I am trying to teach myself some C#.  So I was using the lessons found at:

    ..and eventually I will move on to some books.  From the tutorial:

    This tutorial wrote:
    This code illustrates how changing a property of an object using a particular reference to it is reflected in all other references to it. Note, however, that although strings are reference types, they work rather more like value types. When one string is set to the value of another, eg

    string s1 = "hello";
    string s2 = s1;
    Then s2 does at this point reference the same string object as s1. However, when the value of s1 is changed, for instance with

    s1 = "goodbye";
    what happens is that a new string object is created for s1 to point to. Hence, following this piece of code, s1 equals "goodbye", whereas s2 still equals "hello".

    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.

    I understand the immutability portion, however, and what happens, but I am wondering what the design reason was behind this.  I can pass it off as some type of "backwards compatability with C/C++" mentality, but at what point do you say "let's make strings changable on the fly"? I seem to remember working with a version of BASIC over a decade ago and it had no issues with allowing the user to change the value of a string after the string was created.  I can understand from a stack/heap standpoint how it probably works, but my question is...why not make them changeable? Maybe I am missing something, and again, I am new to C#, although I have looked at some Java code in the past and wondered the exact same thing.