How to clone a generic list in C#?


A list is a Generic collection to hold elements of same datatypes.

To clone a list, you can use the CopyTo method.

Declare a list and add elements −

List < string > myList = new List < string > ();
myList.Add("Programming");
myList.Add("Web Dev");
myList.Add("Database");

Now create a new array and clone the list into it −

string[] arr = new string[10];
myList.CopyTo(arr);

Here is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {

      List < string > myList = new List < string > ();
      myList.Add("Programming");
      myList.Add("Web Dev");
      myList.Add("Database");
      Console.WriteLine("First list...");

      foreach(string value in myList) {
         Console.WriteLine(value);
      }
      string[] arr = new string[10];
      myList.CopyTo(arr);
      Console.WriteLine("After cloning...");

      foreach(string value in arr) {
         Console.WriteLine(value);
      }
   }
}

Output

First list...
Programming
Web Dev
Database
After cloning...
Programming
Web Dev
Database

Updated on: 22-Jun-2020

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements