I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn\'t seem to be an option to do list.Clone()
You can use extension method:
namespace extension
{
public class ext
{
public static List clone(this List t)
{
List kop = new List();
int x;
for (x = 0; x < t.Count; x++)
{
kop.Add(t[x]);
}
return kop;
}
};
}
You can clone all objects by using their value type members for example, consider this class:
public class matrix
{
public List> mat;
public int rows,cols;
public matrix clone()
{
// create new object
matrix copy = new matrix();
// firstly I can directly copy rows and cols because they are value types
copy.rows = this.rows;
copy.cols = this.cols;
// but now I can no t directly copy mat because it is not value type so
int x;
// I assume I have clone method for List
for(x=0;x
Note: if you do any change on copy (or clone) it will not affect the original object.