1

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 ?

Kris-I
  • 18,550
  • 52
  • 145
  • 228
  • Why do you use the `ICloneable` interface? This interface is useless: http://stackoverflow.com/questions/536349/why-no-icloneablet. – Steven Jul 31 '12 at 07:13

3 Answers3

3

Your implementation of Clone is wrong.

Try this:

public object Clone()
{
    return MemberwiseClone();
}
leppie
  • 112,162
  • 17
  • 191
  • 293
1

Your clone method returns the same object.

You should implement it like this

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

    public object Clone()
    {
        return new Person { FirstName = this.FirstName, LastName = this.LastName };
    }
}
mathieu
  • 30,573
  • 4
  • 60
  • 89
1

Apart from the issue with your Clone method inside your Person class you need to return a new list in your extension method also

return collection.Select(item => (T)item.Clone()).ToList();

This is because the Select method is from Linq which uses deferred execution. If you change the original list then the list of 'myCopy' will also change.

aqwert
  • 10,178
  • 2
  • 39
  • 58