473,804 Members | 3,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to Deep Copy properly?

Jax
I have inherited the ICloneable interface and have set up
a public object Clone() method;
This method creates a new version of itself puts all it's
stuff in it(and yes all custom objects within have the
same method) then casts that into and object and passes it
back.

Is this not a deep copy?
It isn't working, I change the value and it satays changes
on the originals, how do I sort this out?

Many thanks to any help given.

jax
Nov 15 '05 #1
3 6347
"Jax" <an*******@disc ussions.microso ft.com> wrote in message
news:00******** *************** *****@phx.gbl.. .
I have inherited the ICloneable interface and have set up
a public object Clone() method;
This method creates a new version of itself puts all it's
stuff in it(and yes all custom objects within have the
same method) then casts that into and object and passes it
back.

Is this not a deep copy?
It isn't working, I change the value and it satays changes
on the originals, how do I sort this out?


You copied the references.
See below:
class CopyExample
{
string str;
public object ShallowCopy()
{
CopyExample ce = new CopyExample();
ce.str = this.str;
return (object)CopyExa mple;
}
public object DeepCopy()
{
CopyExample ce = new CopyExample();
ce.str = this.str.Clone( );
retunr (object)CopyExa mple;
}
}
Nov 15 '05 #2
Hello

For the String type in particular, Clone method returns a reference to the
string itself, this is because strings in .NET are immutable

Best regards
Sherif

"Ayende Rahien" <Ay****@no.spam > wrote in message
news:#F******** ******@TK2MSFTN GP09.phx.gbl...
"Jax" <an*******@disc ussions.microso ft.com> wrote in message
news:00******** *************** *****@phx.gbl.. .
I have inherited the ICloneable interface and have set up
a public object Clone() method;
This method creates a new version of itself puts all it's
stuff in it(and yes all custom objects within have the
same method) then casts that into and object and passes it
back.

Is this not a deep copy?
It isn't working, I change the value and it satays changes
on the originals, how do I sort this out?


You copied the references.
See below:
class CopyExample
{
string str;
public object ShallowCopy()
{
CopyExample ce = new CopyExample();
ce.str = this.str;
return (object)CopyExa mple;
}
public object DeepCopy()
{
CopyExample ce = new CopyExample();
ce.str = this.str.Clone( );
retunr (object)CopyExa mple;
}
}

Nov 15 '05 #3
Hello

An easy way to clone an object, is to serialize it to a memory stream, then
unserialize it again.
But this can be done only when the class has [Serializable] attribute
defined, and all fields in the class whether custom or not must have the
serializable attribute.

[Serializable]
public class Class1
{
}

[Serializable]
public class MyClass : ICloneable
{
// all these fields are serializable
int a;
string b;
double c;
decimal[] d;
Class1 e;

// This field is not serializable so we define the NonSerialized
Attribute
[NonSerialized]
TextBox t;

public object Clone()
{
BinaryFormatter bf = new BinaryFormatter ();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms , bf);
ms.Position = 0;
return bf.Deserialize( ms);
}
}

Best regards,
Sherif

"Jax" <an*******@disc ussions.microso ft.com> wrote in message
news:00******** *************** *****@phx.gbl.. .
I have inherited the ICloneable interface and have set up
a public object Clone() method;
This method creates a new version of itself puts all it's
stuff in it(and yes all custom objects within have the
same method) then casts that into and object and passes it
back.

Is this not a deep copy?
It isn't working, I change the value and it satays changes
on the originals, how do I sort this out?

Many thanks to any help given.

jax

Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3290
by: Tony Johansson | last post by:
Hello! I'm reading in a book about C++ and that is something that sound strange. It says "Pointers have reference-assignment semantics similar to those in Java. For example, after the assignment Student* john = michael; both john and michael share the same object. This type of an assignment is different then value-assignmnet semantics used by class variables, as in
2
12354
by: Alex | last post by:
Entering the following in the Python shell yields >>> help(dict.copy) Help on method_descriptor: copy(...) D.copy() -> a shallow copy of D >>>
4
52312
by: fperfect13 | last post by:
Hi, I wanted to perform a deep copy of an array. Searching on google I ran into different opinions : C# Interview Questions (http://blogs.wwwcoder.com/tsvmadhav/archive/2005/04/08/2882.aspx) 10.What's the difference between the System.Array.CopyTo() and System.Array.Clone()?
4
12468
by: Dennis | last post by:
I have several Data Structures, say "mystruct" which contain arrays of bytes, other structures, etc. I then dimension a variable (var1) as "mystruct" and set the various elements var1 to data. I then dimension another variable (var1save) as "mystruct" and set var1save = var1 with the intent of changing var1 data elements and subsequently reasigning var1 back to it's original values of var1save. VB.Net makes only a shallow copy of var1...
6
4328
by: Desmond Cassidy | last post by:
Hi, I'm sure this has been asked several times before but I'll risk it ;-) If I wish to save an Arraylist to another Arraylist and work on te original without affecting the contents of the new or saved Arraylist, how is it done. It always seems to create a shallow copy i.e. by Reference. I even tried passing the original Arraylist to a function by Value and return a copy....after an arraylist.clear on the original it still clears the...
5
25655
by: BenW | last post by:
Hello, What is the easiest way to make "deep copy" of my Hashtable? How about with other Collection classes in C#, any documents available? I don'r actually understand why Framework's Collection classes does not support deep copy methods by theself, only Clone with shallow copy.
2
10121
by: bonk | last post by:
I have come across the need to distinguish between the creation of a deep and a shallow copy and with great interest I have read this article: http://blogs.msdn.com/brada/archive/2004/05/03/125427.aspx This artivle seems to hint that I should not use System.IClonable but instead define my own interface(s) for cloning. Now since this article is rather old and since they did not obsolete IClonable there might be a new "best practise".
13
5027
by: blangela | last post by:
I have decided (see earlier post) to paste my Word doc here so that it will be simpler for people to provide feedback (by directly inserting their comments in the post). I will post it in 3 parts to make it more manageable. Below is a draft of a document that I plan to give to my introductory C++ class. Please note that I have purposely left out any mention of safety issues in the ctors which could be resolved thru some combination...
4
3150
by: shuisheng | last post by:
Dear All, Is there any easy way to make sure all my object copies are deep copy or shallow copy? I do not like to implement it in each class one by one. Thanks, Shuisheng
3
8754
by: raylopez99 | last post by:
The "C# Cookbook" (O'Reilly / Jay Hilyard), section 3.26, is on deep cloning versus shallow cloning. The scanned pages of this book are found here: http://www.sendspace.com/file/mjyocg (Word format, 3 pp) My question, coming from a C++ background where deep copying is done, is why in C# you would do either deep or shallow copying as suggested by O'Reilly (using the "ICloneable" inhereited interface), at least for the .NET framework. ...
0
9707
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10338
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10323
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10082
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7622
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6856
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3823
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2997
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.