Tuesday, July 28, 2009

Please help me in general C# understanding...?

Hello, and thank you again because of your try to help me.





My question is as follows:





I Have a class named MyClass. I make an instance of that and name it MyInstance1. Then I define another MyClass object named MyInstance2. After all I do this:





MyInstance2=MyInstance1;





After this line, whenever I use the MyInstance2 members (such as methods, properties, fields and etc...) in my current procedure It is going to be same as MyInstance1, In the Matter that MyInstance1 and MyInstance2 are pointing to a same area in the memory. (a little same as union variables in C %26amp; C++). I know that is a general feature of C#.





But I want to do that like in C. I mean I want to make a copy of MyInstance1 and name it as MyInstance2 (not defining a union which points to same area in memory) and these two instances must be apart.





Also I prefer doing so in Managed mode (Not Unmanaged way).





Be Succeed,


Babax.

Please help me in general C# understanding...?
You're talking about cloning the instance. Depending on what your class is, you may want a deep or shallow copy. If you're looking for a shallow copy, you want to look at the MemberwiseClone method of Object. Otherwise, you'll want to write up your own copy logic and use IClonable.Clone.





As a point of note, all object references in C# are just that: object references. The best way to compare this back to C is more like you've malloc'ed a region of memory for your use, and you're setting a second pointer to it, but to get a copy, you have to memcopy it.





Good luck.
Reply:Class objects are refernce type. So what you found is the expected behavior. Here when you assign myinstance2=myinstance1, myinstance2 is a reference to myinstance1. Any change to myinstance2 will reflect to myinstance1. So that means its not a seperate copy.





You can see more of this if you search for Deep Copy and Shallow Copy. The current situation is Shallow Copy.





You can implement a deep copy is shown on link below.

covent garden

No comments:

Post a Comment