c# object = object

Started by
3 comments, last by tnts 18 years, 11 months ago
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?
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.
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

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.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
everything is clear now;
thank You

This topic is closed to new replies.

Advertisement