Hashtable cloning :: deep solution using serialization

O

oDDskOOL

I realized today that the Hashtable.Clone only produces a shallow
copy... that makes me go mad that M$ doesn't even provide a deep copy
ctor for the Hashtable class !

mighty tech ducks might reply "oh but what if the types in hastable
don't have copy ctors defined? that could lead to dangerous
situations".

well, but was it a significant effort to provide a copy ctor / deep
clone method to this class for objects that provide the IClonable
interface? WTF with M$ that made 'em say in the MSDN that Hashtable
implements IClonable and _don't_ provide a deep copy ctor???

i am wondering... but meanwhile i thought of a trick to do smthg like a
de"ep clone using serialization (=> for objects that implements it) :

1) serialize your hashtable
2) deserialize it into a new one
3) garbage the serialization

to serialiaze, you might want to use this code

<code>
using System;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;


/// <summary>
/// Deep copy of Serializable items
/// </summary>
public class ObjectUtils
{
static BinaryFormatter binForm=new BinaryFormatter();

public static object CloneBySerialization(object source)
{
MemoryStream ms=new MemoryStream();
binForm.Serialize(ms,source);
return binForm.Deserialize(new MemoryStream(ms.ToArray()));
}

}
}
</code>

but is there another way, perhaphs more elegant???

(err i dont' want to implement a Hashtable deep copy :: it's M$ work:)
 
N

Nicholas Paldino [.NET/C# MVP]

oDDskOOL,

Nope, that's pretty much the most elegant way.

It should be noted that MS doesn't give guidance on the implementation
of IClonable. Doing so would lock them into a pattern, and given the
widespread use of this interface, it is impossible for them to determine
what the best approach would be.

Granted, it might help to have a IDeepClonable and IShallowClonable
interface, but then again, there would be bickering over the exact meaning
of those as well.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top