Alex Rivera | Logout

C# Copy Array by Value

Asked 2009-07-31T22:33:33.473
27

I have a typed array MyType[] types; and i want to make and independant copy of this array. i tried this

MyType[] types2 = new MyType[types.Length] ;

types2 = types ;

but this create a reference to the first. I then tried

Array.Copy( types , types2 , types.Length ) ;

but I have the same problem: changing a value in the first array changes the value in the copy as well.

How can I make a completely independent or deep copy of an Array, IList or IEnumerable?

Edit
Report

1 Answer

7

If your type is serializable you can use serialization techniques to get a copy of your array (including deep copies of the items):

private static object GetCopy(object input)
{
    using (MemoryStream stream = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, input);
        stream.Position = 0;
        return formatter.Deserialize(stream);
    }
}

To use it:

MyType[] items = new MyType[2];
// populate the items in the array

MyType[] copies = (MyType[])GetCopy(items);
answered 2009-07-31T22:49:50.507

Your Answer