C# Reference type assignment VS value type assignment

后端 未结 6 1393
自闭症患者
自闭症患者 2020-12-06 22:27

I understand the theoretical concept that assigning one reference type variable to another, only the reference is copied, not the object. assigning one value type variable t

6条回答
  •  生来不讨喜
    2020-12-06 23:20

    On my system, those two code blocks produce the following output:

    Original Employee Values:

    joe = Joe
    bob = Bob
    
    Values After Reference Assignment:
    joe = Joe
    bob = Joe
    
    Values After Changing One Instance:
    joe = Bobbi Jo
    bob = Bobbi Jo
    

    ...and...

    Original Height            Values:
    joe = 71
    bob = 59
    
    Values After            Value Assignment:
    joe = 71
    bob = 71
    
    Values After            Changing One Instance:
    joe = 65
    bob = 71
    

    The difference seems self-evident. In the first sample, changing one of the values affects both references, because they are both referencing the same underlying object. In the second sample, changing one of the objects affects only that object, because when value types are copied, each object receives it own private copy. When you say bob = joe; in the second sample, you;re not assigning a reference (the comment is misleading). What you're doing is creating a new instance of the Height struct, copying all the values from joe and storing the new object as bob.

提交回复
热议问题