SonnyListon
SonnyListon

Reputation: 13

C# Object reference to another object's property

Say I have an object's property pointing to different objects during its lifetime.

MyClassInstance.MyProperty = MyOtherObject1;

Later in the application I get this:

MyClassInstance.MyProperty = MyOtherObject2;

And so on. My understanding is that MyOtherObject1 and MyOtherObject2 will be pointing to the same address in memory, which I want to avoid. How can I make sure MyOtherObject1 and MyotherObject2 are 2 completely different entities?

Upvotes: 0

Views: 50

Answers (1)

Andreas Tsiapis
Andreas Tsiapis

Reputation: 36

If MyOtherObject1 and MyOtherObject2 are different objects, making the MyClassInstance.MyProperty equal to them, will not result in these 2 being the same.

MyClassInstance.MyProperty = MyOtherObject1;

This means any changes to MyClassInstance.MyProperty will change MyOtherObject1, as they effectively point to the same memory space.

MyClassInstance.MyProperty = MyOtherObject2;

This means that MyProperty now points to the same memory space as MyOtherObject2. Changes to MyProperty will leave MyOtherProperty1 unaffected.

Upvotes: 2

Related Questions