locked
reference type (string) RRS feed

  • Question

  • User-1232255770 posted

    a string is a reference type (so a pointer to an address) , i want to understand this so the following code

      string one = "test1";
                string copyone = one;
                one = "test2";
               string  tmpstr = one  + "" + copyone;

    the values of one and copyone in the tmpstr are ,"test2" , "test1", 

    i would expect "test2", "test2"  because its a reference , (the way it behaves is like a value type , i think)

    what am i missing here ?

    Tuesday, June 5, 2018 10:31 AM

Answers

  • User-369506445 posted

    hi

    string one = "test1";

    one is equal to the address where "test1" is stored, let's say 0x0000AAAA

    string copyone = one;

    copyone points to the same address as one hence, its value is the same as one. Both have values 0x000AAAA

    Strings are immutable, meaning you cannot modify a string, anytime you assign a new value or a modification, you are creating a new string somewhere else in memory while the previous one gets ready for GC, if needed (not in our case actually). At that point, one still has value 0x0000AAAA while copyone  has a new one 0X0000BBBB.

    please refer to below link:

    https://stackoverflow.com/questions/36276619/string-is-reference-type-but-why-it-work-as-a-value-type-when-its-assignment-up

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 5, 2018 11:09 AM