Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any better deep clone methods for list? [duplicate]

Tags:

c#

deep-copy

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?

like image 259
Jesper Avatar asked Feb 05 '23 08:02

Jesper


1 Answers

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()); 
like image 192
Tim Schmelter Avatar answered Feb 20 '23 09:02

Tim Schmelter