Why strings behave like ValueType

后端 未结 7 2009
感动是毒
感动是毒 2020-12-16 23:44

I was perplexed after executing this piece of code, where strings seems to behave as if they are value types. I am wondering whether the assignment operator is operating on

7条回答
  •  我在风中等你
    2020-12-17 00:12

    You're not changing anything about the object a1 points to, but instead changing which object a1 points to.


    (source: morethannothing.co.uk)

    Your example replaces "new Person { … }" with a string literal, but the principle is the same.

    The difference comes when you're changing properties of the object. Change the property of a value type, and it's not reflected in the original.


    (source: morethannothing.co.uk)

    Change the property of a reference type, and it is reflected in the original.

    p.s. Sorry about the size of the images, they're just from something I had lying around. You can see the full set at http://dev.morethannothing.co.uk/valuevsreference/, which covers value types, reference types, and passing value types by value and by reference, and passing reference types by value and by reference.

提交回复
热议问题