• Advertisement
Sign in to follow this  

c# object = object

This topic is 4686 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

what is going on when I create something like: Class1 obj1 = new Class1; Class1 obj2 = new Class1; obj1.field1 = something; obj2.field1 = somethingElse; obj1 = obj1; Is memory allocated to obj1 being lost and obj1 points to obj2, or obj1 is overwritten with data from obj2 and there are two independent objects in the memory?

Share this post


Link to post
Share on other sites
Advertisement
I guess you meant obj1 = obj2

Then the memory obj1 is referencing will be garbage collected (in the near future) and obj1 is a reference to the memory obj2 is refering to.

Share this post


Link to post
Share on other sites
I'm a little rusty on my C#, but all C# objects(Class instances) are references. If you assign obj1 = obj2; Obj1 will "cease to exist"(It becomes unreachable) and the reference to obj2 is copied into obj2.

Obj1 and Obj2 now reference to the same memory location, and if you do Obj2 = null;, then Obj1 will still be valid.

If you want to copy Obj2 into Obj1, look into the ICloneable interface.

Toolmaker

Share this post


Link to post
Share on other sites
It depends.

If Class1 is a struct, then a bitwise copy is performed during the assignment. (Structs are value types.) If Class1 is a class, then only the references are changed. If obj1 is the last reference, then it is eligible for finalization and garbage collection at some indeterminate point in the future. Until this happens, the object will still exist, but it will be inaccessible.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement