Reputation: 10055
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?
Upvotes: 0
Views: 942
Reputation: 205589
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();
Upvotes: 1
Reputation: 100527
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();
}
Upvotes: 0