none
Immutable in C#

    Question

  • What is immutable?

     

    The dictionary meaning says that, “whose state is not changed is known as immutable”.

     

    Why are strings immutable? What does it mean?

     

    String A = “test”;

     

    A = “sample”;

     

    So actually how state is related to string here in the above example and can you please give me an example where state is changed?

     

    If strings are immutable, then are all Reference Types immutable?

     

    After doing some search I came to know that some Value Types and Reference Types are immutable? Is that correct?

    Wednesday, May 11, 2011 2:08 PM

Answers

  • strings are immutable remember, if there were such an instance method method (not that I know of) A.Concat("color") wouldn't actually change A but instead return a new string so you would end up with two different strings.
    For example:

    string A = "ForeColor";
    string B = A.Remove(4);
    // A = "ForeColor"
    // B = "Fore"

    Other numeric data types are mutable.

    /Calle


    - Still confused, but on a higher level -
    • Marked as answer by winnster Wednesday, May 11, 2011 6:53 PM
    Wednesday, May 11, 2011 6:48 PM

All replies

  • A string is considered immutable when concatenation comes into the picture. When you perform "test" + "a" the original string is still in tact and a new string "testa" So now you have 2 strings. "test" and "testa" The stringbuilder class was designed to eliminate this potentially crippling effect especially found in large concatenations.

    Adam


    Ctrl+Z
    Wednesday, May 11, 2011 2:14 PM
  • It's a pattern used in programming languages. It means that once a string is made, it is stored internally in a kind of lookup table, and it is never changed again. If you create an exact same string, it' isn't really created, it's already there. If you perform string function, the string is not changed; a new string is created every time. That is why repeatedly adding to a string is so unefficient; using as stringbuilder object remedies that, because that is a 'mutable' kind of string.

    Not all reference types are immutable; most of them are not.

    Apart from the stringbuilder story, it is not really important for a programmer to know if a type is immutable.


    Regards, Nico
    Wednesday, May 11, 2011 2:21 PM
  • so you are saying that even the reference of the string now points to a new value "testa", "test" will still exist and will not be cleared by GC on heap,

    but all the reference types behave the same way, isn't it? because what I understood is whenever a new value is assigned to a reference type it justs points to a new memory location and the old one gets cleared by Garbage Collector

    Please let me know, because I am stuck with knowing the basics

    Wednesday, May 11, 2011 2:27 PM
  • No, if it's not referenced, it is GC'd, that's the general rule.
    Regards, Nico
    Wednesday, May 11, 2011 2:37 PM
  • It's gets cleared by the garbage collector at the GC's earliest convenience...lol...that's my best answer....which is usually when it become out of scope.

    Adam


    Ctrl+Z
    Wednesday, May 11, 2011 2:40 PM
  • No, if it's not referenced, it is GC'd, that's the general rule.
    Regards, Nico

          String A = "test";

         A = "testa"

     

        here "A"  is now referencing to "testa", so "test" should be GC'ed, Is that correct?

     

          similarly,

          String B = "newTest";

          B = "Newtest" + "c";

         here "B" is now referencing to "Newtestc", so "newTest" should be Gc'ed, Is that correct?

     

    Please answer both the questions and if they are Gc'ed differently,  please explain why it does that way

    Wednesday, May 11, 2011 2:44 PM
  • No, if it's not referenced, it is GC'd, that's the general rule.
    Regards, Nico

          String A = "test";

         A = "testa"

     

        here "A"  is now referencing to "testa", so "test" should be GC'ed, Is that correct?

     

          similarly,

          String B = "newTest";

          B = "Newtest" + "c";

         here "B" is now referencing to "Newtestc", so "newTest" should be Gc'ed, Is that correct?

     

    Please answer both the questions and if they are Gc'ed differently,  please explain why it does that way


    yes, also "c" is gc'd.
    Regards, Nico
    Wednesday, May 11, 2011 2:47 PM
  • Reference assignment and garbage collection have nothing to do with the concept of immutability.

    Immutable simply means that the state of the object cannot change - effectively, this means the object has no data members (fields or properties) that have values that can be changed once the object is created.

    The reason we talk about strings in .NET as being immutable is because this is in contrast to C++ strings.  C++ strings are either char* pointers or STL strings.  With a char* pointer, you can change the letter at a speciic position in the string using the indexer operator or pointer arithmetic, e.g.,

    char* hello = "Hello";

    hello[1] = 'a'; // "hello" is now "hallo"

    (Actually, I think you're not allowed to modify strings defined as literals like that.  It's been about 8 years since I've done any C++ work but I seem to recall the above being illegal.   But you get the idea).

    I don't remember anything about STL strings syntax wise, but I know for certain that they act the same way.  You can change portions of the string's memory to change the characters contained inside it.

    .NET strings do not behave this way.  There are a lot of reasons, but one of those is the fact that .NET interns its strings which means it keeps a string cache - if you assign 100,000,000 string variables to the string "Hello", only 5 characters are allocated and each variable points to those 5 characters in memory.  If string were mutable, it would be impossible to do that.

    Here's another example:

    public class Mutable
    {
      public string DataMember { get; set; }
    }
    
    public class Immutable
    {
      public Immutable(string memberValue)
      {
        DataMember = memberValue;
      }
      public string DataMember { get; private set; }
    }
    

    The Immutable class is immutable because it doesn't let you change the value of DataMember because the setter is private.  There is no language construct or keyword that you can use to mark a class as immutable.  It's merely an aspect of the class.

    As far as design goes, the general rule is: always make a class immutable unless it must contain a changeable state.  Immutable objects have a number of advantages over mutable classes.  One example is that immutable classes can be safely used as keys in dictionaries in hashes, whereas mutable classes can't be.  (Technically they can, it's just not safe to do so).

    Evan

    Wednesday, May 11, 2011 2:49 PM
  • Regardless of when the GC takes action (which is at an undetermined time), the idea is to be proactive not reactive...meaning dont' rely on the GC to clean up your mess.

    Adam


    Ctrl+Z
    Wednesday, May 11, 2011 2:51 PM
  • Immutable objects are also well suited for multithreaded programming since no thread is allowed to change the state of the object.

    /Calle


    - Still confused, but on a higher level -
    Wednesday, May 11, 2011 3:14 PM
  • I am still not yet totally understood, could you all, please tell me what are you referring "State" to?


    Wednesday, May 11, 2011 4:14 PM
  • A state is the overall view of an object or multiple objects at any given time. A simple example would be a class which has two properties:

    class Person
    {
    	public string Name;
    	public int Age;
    }
    

    If you create an instance of this class then the initial state of that object would be that Name=null and an Age=0. This is the state of the object after creation. Now if you would assign a name and an age so that Name and Age would have changed you would say that the object's state has changed. State is just a definition of the object data.

    When talking about immutable objects you would mean that after creation the state of these objects would not change, not from client code or from within the object. Often you would make sure that no code could actually change the state of the object. In the example above any code could set a new value for Name or Age meaning that the object would be mutable. To make it immutable you would need to provide only read access to those properties.

    /Calle


    - Still confused, but on a higher level -
    Wednesday, May 11, 2011 5:57 PM
  • Calle,

    When talking about immutable objects you would mean that after creation the state of these objects would not change, not from client code or from within the object. Often you would make sure that no code could actually change the state of the object. In the example above any code could set a new value for Name or Age meaning that the object would be mutable. To make it immutable you would need to provide only read access to those properties.

    So now I understood that the state of the object changes when a new value is assigned

    ok, till now it is clear

     

    from the below example why does the state of string doesn't change?

    string A = "apple";

    A.Concat("color");

    so here, the state of string A is changed? Isn't that correct? If it is correct, then it is mutable, and not immutable. Not only string, for any datatype state changes, so all the datatypes are mutable then

     

     

    Wednesday, May 11, 2011 6:29 PM
  • strings are immutable remember, if there were such an instance method method (not that I know of) A.Concat("color") wouldn't actually change A but instead return a new string so you would end up with two different strings.
    For example:

    string A = "ForeColor";
    string B = A.Remove(4);
    // A = "ForeColor"
    // B = "Fore"

    Other numeric data types are mutable.

    /Calle


    - Still confused, but on a higher level -
    • Marked as answer by winnster Wednesday, May 11, 2011 6:53 PM
    Wednesday, May 11, 2011 6:48 PM
  • Thankyou Calle, and all who has contributed to this post

     

    I appreciate your patience to explain the answers very detail which encourages newbies to learn

    Wednesday, May 11, 2011 6:55 PM
  • Thankyou Calle, and all who has contributed to this post

     

    I appreciate your patience to explain the answers very detail which encourages newbies to learn

     

    Thanks

    Wednesday, May 11, 2011 6:55 PM
  • Actually, threads like this discourages me to continue programming...lol
    Ctrl+Z
    Wednesday, May 11, 2011 7:07 PM