0
public class MyStuff : ICloneable
{
    public int A {get;set;}
    public int B {get;set;}

    public object Clone()
    {
        MyStuff Copy = (MyStuff)MemberwiseClone();
        return Copy;
    }
}

Now lets assume i have an array of MyStuff

MyStuff[] MyStuffObjs = PopulateMyStuff();

What is the quickest/easiest way to create a clone of MyStuffObjs implementing the Clone method?

I know i can iterate through the collection and copy each one.

List<MyStuff> NewStuff = new List<MyStuff>();
foreach(var Stuff in MyStuffObjs)
{
    NewStuff.Add(Stuff.Clone());
}
return NewStuff.ToArray();

Surely there is a better way?

CathalMF
  • 9,705
  • 6
  • 70
  • 106

2 Answers2

1

You can use Linq for that:

return MyStuffObjs.Select(item => (MyStuff)item.Clone()).ToArray();

You can even create a helper method like this

public static class MyExtensions
{
    public static T[] DeepClone<T>(this T[] source) where T : ICloneable
    {
        return source.Select(item => (T)item.Clone()).ToArray();
    }
}

and use it as follows

return MyStuffObjs.DeepClone();
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
0

Just Select/ToArray would be shorter, but really there is nothing significantly better than iterating over all items and calling Clone.

Shorter code:

 return MyStuffObjs.Select( x=> x.Clone()).ToArray();

A bit faster code - pre-allocate array instead of using list:

MyStuff[] cloned = new MyStuff[MyStuffObjs.Length];
for (var i = 0; i < cloned.Lenght; i++)
{
    cloned[i] = MyStuffObjs[i].Clone();
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179