So I needed a method to deep clone. I wanted one list of cards to equal another list of cards, but then I also wanted to modify one of the clones.
I made a method to copy the list like this:
public List<Card> Copy(List<Card> cards)
{
List<Card> clone = new List<Card>();
foreach (var card in cards)
{
clone.Add(card);
}
return clone;
}
and use it like this:
_cards = new List<Card>();
_thrownCards = new List<Card>();
_cards = Copy(_thrownCards);
_thrownCards.Clear();
I'm not experienced in C#, but somehow my gut feelings tells me my copy method could be made simpler. Isn't there any other way you could deep copy a list? I tried using MemberWiseClone, but that just created references to the same object, not cloning it(maybe I misinterpreted the MemberWiseClone method).
Do anyone have any tip how simply clone a list object?
That's not a real deep-copy because the Card
instances are still the same, only the list is different. You could have this much simpler:
List<Card> cloneList = cards.ToList();
You need to "copy" all properties of the Card
instances as well:
public List<Card> Copy(List<Card> cards)
{
List<Card> cloneList = new List<Card>();
foreach (var card in cards)
{
Card clone = new Card();
clone.Property1 = card.Property1;
// ... other properties
cloneList.Add(clone);
}
return cloneList;
}
You could also provide a factory method that creates a clone of a given Card
instance:
public class Card
{
// ...
public Card GetDeepCopy()
{
Card deepCopy = new Card();
deepCopy.Property1 = this.Property1;
// ...
return deepCopy;
}
}
Then you have encapsulated this logic in one place where you can even access private
members(fields, properties, constructors). Change the line in the Copy
method above to:
cloneList.Add(card.GetDeepCopy());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With