Can somebody please help me to write a DeepCopy routine for this matrix class I have ? I dont have a great deal of experience in C#.
public class Matrix<T>
{
private readonly T[][] _matrix;
private readonly int row;
private readonly int col;
public Matrix(int x, int y)
{
_matrix = new T[x][];
row = x;
col = y;
for (int r = 0; r < x; r++)
{
_matrix[r] = new T[y];
}
}
}
Thanks in advance
The simplest way of deep copying would be using some kind of serializer (for instance
BinaryFormatter), but this requires not only your type to be decorated asSerializable, but also the type T.An example implementation of that could be:
The issue here, is that you have no control over which type is supplied as generic type parameter. Without knowing more about which kind of types you wish to clone, an option might be to put a generic type constraint on T to only accept types that implement
ICloneable.In which case you could clone
Matrix<T>like so: