473,729 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Deep copy

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.

bmw
Nov 26 '05 #1
5 25644
On Sat, 26 Nov 2005 16:26:02 +0200, "BenW" <bm*@mailer.sma rt.com>
wrote:
What is the easiest way to make "deep copy" of my Hashtable?
There is no easy way. You must define your own deep copy method on
the element type of your hashtable, and an additional deep copy method
for your hashtable that calls the element copy method on all elements.
How about with other Collection classes in C#, any documents available?
No documents, same as above. The Framework does not support any deep
copies of collections by default.
I don'r actually understand why Framework's Collection classes does not
support deep copy methods by theself, only Clone with shallow copy.


A standard deep copy support would have to be ubiquitous. Collections
can contain anything, and that "anything" could be a type that
contains other nested objects, and so on. A deep copy must recurse
through all those levels. The Framework designers didn't provide a
default deep copy method on System.Object, hence they couldn't very
well provide one for System.Collecti ons types (how to copy elements?).
--
http://www.kynosarges.de
Nov 26 '05 #2
> What is the easiest way to make "deep copy" of my Hashtable?
The easiest way to deep copy a Hashtable is to use serialization as shown
in the example below.

using System;
using System.Collecti ons;
using System.Diagnost ics;
using System.IO;
using System.Runtime. Serialization.F ormatters.Binar y;

public class DeepCopyExample
{
public static void Main()
{
Hashtable t1=new Hashtable();
t1.Add("Key1"," Value1");
t1.Add("Key2"," Value2");
MemoryStream s=new MemoryStream();
BinaryFormatter f=new BinaryFormatter ();
f.Serialize(s,t 1);
s.Position=0;
Hashtable t2=(Hashtable) f.Deserialize(s );
Debug.Assert(t2["Key"]==t1["Key1"]);
}
}

You can use serialization to deep copy any type that is serializable.

Anders Norås
http://dotnetjunkies.com/weblog/anoras
Nov 26 '05 #3
On Sat, 26 Nov 2005 14:11:41 -0800, Anders Norås
<an**********@o bjectware.no> wrote:
The easiest way to deep copy a Hashtable is to use serialization as shown
in the example below.


That's a clever method but I wonder about the runtime performance
since you get the overhead of a MemoryStream, and also of member-wise
reflection for the serialization of all fields in all elements.

Of course you could implement ISerializable to avoid the cost of
reflection but in that case your way wouldn't be easy anymore...

By the way, there is actually no difference between a deep copy and a
shallow copy in your example. Your hashtable contains only strings,
and .NET strings are immutable.
--
http://www.kynosarges.de
Nov 27 '05 #4
> That's a clever method but I wonder about the runtime performance
since you get the overhead of a MemoryStream, and also of member-wise
reflection for the serialization of all fields in all elements. As you point out there is a performance overhead with serialization, but
still this is the easiest way to deep copy a serializable object. I often
use serialization to clone objects and I've seldom had any performance problems
when doing this.
Of course you could implement ISerializable to avoid the cost of
reflection but in that case your way wouldn't be easy anymore... Reflection isn't as expensive as many people tell you. Try to use serialization
first and fall back to implementing ISerializable, or IClonable, if you experience
performance problem.
By the way, there is actually no difference between a deep copy and a
shallow copy in your example. Your hashtable contains only strings,
and .NET strings are immutable.

I'm aware of this, but I wanted to keep my example simple. This works for
*any* serializable object and you're guarandteed to get a deep copied clone.

Regards,
Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 27 '05 #5
You must create a clone method that first use MemberwiseClone () method to
create a new cloned object an then, for each field of your class that is a
"reference" (not a struct), you must clone the field recursively. This is
the only way with C# to do an efficient cloning.

Hope it helps.
"BenW" <bm*@mailer.sma rt.com> a écrit dans le message de
news:O9******** ******@TK2MSFTN GP10.phx.gbl...
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.

bmw

Nov 28 '05 #6

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

Similar topics

5
3286
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
12349
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
52301
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
12458
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
4318
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...
2
10115
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
5012
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
3145
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
8748
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
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9280
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
9200
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
9142
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
6722
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
6016
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
4525
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...
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2162
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.