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?
cards.ToList()but ifCardis a reference type you'll need to clone each list element as well to get a deep copy.Cardinstances are not cloned but just copied to another list (assuming they are not structs).new List<Card>()you don't actually need to initialize _cards first. You could use your function like this:_thrownCards = new List<Card>(); ...; _cards = Copy(_thrownCards); _thrownCards.Clear();Also, what you are actually doing in your Copy function is a shallow clone. Here's a Stackoverflow question about the difference between the two.