CODECUBE VENTURES

Properly cloning an ArrayList

Having run into this issue before, I was quickly able to diagnose the problem. Unfortunately, I was dealing with more complex objects than before. Thankfully, I remembered the talk Jason Beres gave at ONETUG about serialization.

While making a modification to the ASP.NET forums (adding threaded view support to the 2.0 codebase), I was getting an exception thrown after I re-ordered the ArrayList of posts for the threaded display. The code was trying to retrieve the ArrayList from the cache, and it was coming out empty for some reason. Luckily, as I mentioned before, I quickly diagnosed this problem as being related to the fact that I was dealing with reference types.

Remembering that the StreamingContextStates has a "Clone" enum, I figured I'd just try to serialize/deserialize the thing and hopefully it would come out on the other end as a different reference. It worked! had to add the [Serializable] decoration to a few classes, but other than that it was pretty painless.

disclaimer: My application is only calling this function once per page request so I have not stress tested this and as such, I have not idea how it will scale. That being said, it works just fine for what I'm using it for.

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections;

/// <summary>
/// Creates a clone of an ArrayList object
/// </summary>
/// <param name="origList">
/// ArrayList to be deep cloned
/// </param>
/// <returns>
/// A completely new instance that what was passed in
/// </returns>
private ArrayList DeepClone(ArrayList origList)
{
MemoryStream mem = new MemoryStream();
try
{
BinaryFormatter bf = new BinaryFormatter(null,
new StreamingContext(StreamingContextStates.Clone));
bf.Serialize(mem, origList);
mem.Seek(0, SeekOrigin.Begin);
return (ArrayList)bf.Deserialize(mem);
}
catch (Exception ex)
{
throw new ApplicationException("Deep copy operation failed", ex);
}
finally
{
mem.Close();
}
}

Latest post: Digging Up the First Version of CodeCube

See more in the archives