Search code examples
c#extension-methodsclone

Deep copy of List<T> with extension method


I have this class :

public class Person : ICloneable
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public object Clone()
    {
        return this;
    }
}

An extension method :

public static class MyHelper
{
    public static IEnumerable<T> Clone<T>(this IEnumerable<T> collection) where T : ICloneable
    {
        return collection.Select(item => (T)item.Clone());
    }
}

I'd like use it in this case :

var myList = new List<Person>{ 
    new Person { FirstName = "Dana", LastName = "Scully" },
    new Person{ FirstName = "Fox", LastName = "Mulder" }
};

List<Person> myCopy = myList.Clone().ToList<Person>();

When I change in the "immediat window" a value of myCopy, there is a change in the orginial list too.

I'd like have both list completely independent

I missed something ?


Solution

  • Your implementation of Clone is wrong.

    Try this:

    public object Clone()
    {
        return MemberwiseClone();
    }