C# Copy Array by Value

Based on the first post, all he needs is this for “an independent copy of the array”. Changes to the shallowCopy array itself would not appear in the types array (meaning element assignment, which really is what he showed above despite saying “deep copy”). If this suits your needs, it will have the best performance.

MyType[] shallowCopy = (MyType[])types.Clone();

He also mentions a “deep copy” which would be different for mutable types that are not recursive value-type aggregates of primitives. If the MyType implements ICloneable, this works great for a deep copy:

MyType[] deepCopy = (MyType[])Array.ConvertAll(element => (MyType)element.Clone());

Leave a Comment