Cloning Generic list?

Is there a better way to shallow-clone a generic List<> than create a new List<> with the old list as the constructor's argument

List<Foo> list1 = new List<Foo>();
// Add a zillion references to list1
List<Foo> list1Copy = new List<Foo>(list1);

The generic lists don't seem to provide the Clone() method. Creating a custom, inheirted List<> is something I'd like to avoid.



Answer this question

Cloning Generic list?

  • FSOL

    List<Foo> mylist = new List<Foo>();
    //Add some references
    List<Foo> mylist_with_cloned_members =
    new List<Foo>( (Foo[])mylist.ToArray().Clone() );

  • Thomas Thayil

    Nevermind, thats wrong
  • Sushil Chordia

    Implement Icloneable interface in Foo Class.

    List<Foo> cloneFoos = new List<Foo>();

    foreach(Foo f in Foos){

    cloneFoos .Add((Foo)f.Clone());

    }



  • clark121121

    I don't think I understand why you want to avoid


    List<foo> list1Copy = new List<foo>(list1);
     


    What would Clone() provide that this technique does not

    -Tom Meschter
    Software Dev, Visual C# IDE



  • Cloning Generic list?