1

What am I missing below? When I try list.Clone() Clone doesn't show up in list.

https://stackoverflow.com/a/222640/139698

class Program
{
    static void Main(string[] args)
    {
        List<Customer> list = new List<Customer>();
        list.Clone() //There is no Clone method in the list
    }
}

public static class Extensions
{
    public static IList<T> Clone<T>(this IList<T> listToClone) where T : ICloneable
    {
        return listToClone.Select(item => (T)item.Clone()).ToList();
    }
}

public class Customer
{
    public string ContactName { get; set; }
    public string City { get; set; }
}
Community
  • 1
  • 1
Rod
  • 14,529
  • 31
  • 118
  • 230

2 Answers2

5

Customer has to implement ICloneable because your generic condition says T has to implement ICloneable.

public class Customer : ICloneable

Sheridan Bulger
  • 1,214
  • 7
  • 9
  • like this? return this.MemberwiseClone(); – Rod Dec 18 '12 at 20:24
  • That's a way of implementing the Clone function, or you can write your own Clone. What matters is full implementation of the ICloneable interface, no matter how it's done. – Sheridan Bulger Dec 18 '12 at 21:18
0

You will need to implement ICloneable interface on Customer class. Also as the extension method has been defined for IList<T> where T is ICloneable, you may want to use below syntax

        IList<Customer> list = new List<Customer>();
        list.Clone(); 

The Clone() extension method will not be visible if Customer doesn't implement ICloneable

jags
  • 2,022
  • 26
  • 34
  • There is no need to use `IList` here, `List` would have worked as well, even though the extension method is for `IList`. – svick Oct 12 '12 at 02:26