Wednesday, November 23, 2005

Deep copy of Hashtable

In order to solve my problem of returning a hashtable by reference (see previous post), I first tried to use Hashtable.Clone() to give me a copy of the hashtable. However since Clone() only does a shallow copy of the hashtable, this did not work since the hashtable contained Objects and changing them in the calling code caused side-effects in the originating class. So what was needed was a deep copy of the hashtable and this proved to be really simple:

private Hashtable mMeasurements = new Hashtable();
...
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms,mMeasurements);

ms.Seek(0,SeekOrigin.Begin);
clonedMeasurements = (Hashtable)bf.Deserialize(ms);

Are there any concerns regarding this code?

1 comment:

ht said...

I have no concerns regarding your code. I'm more concerned what your unit tests have to say about it. Unit testing a mock-code might sound a bit strange, but can give you value as in this case.