c# strings are reference types - why when i change reference A's value, reference B doesn't change?

后端 未结 4 942
無奈伤痛
無奈伤痛 2020-12-12 05:08

If strings in .NET are reference types, in the below code, why doesn\'t string2 change to \"hi\" after string1 is changed?

static void IsStringReallyAReferen         


        
4条回答
  •  不思量自难忘°
    2020-12-12 05:24

    When you assigned "hi" to string1, what happened is that the variable string1 got assigned a new reference to an object on the heap which contains the text "hi".

    Whereas, the variable string2 is still holding a reference of the object which has text "hello" within it.

提交回复
热议问题