Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable.Copy() or DeepClone. Which one to choose?

I have a confusion

Scenario:

I want to create a copy of a DataTable to be added to another DataSet. There are 2 ways to do it (AFAIK):

1. Make a Copy using DataTable.Copy()
2. Make a Deep Clone using 

public static T DeepClone<T>(this T source)
{
    if (!typeof(T).IsSerializable)
        throw new ArgumentException("The type must be serializable.", "source");

    // Don't serialize a null object, simply return the default for that object
    if (Object.ReferenceEquals(source, null))
        return default(T);

    IFormatter formatter = new BinaryFormatter();
    Stream stream = new MemoryStream();
    using (stream)
    {
        formatter.Serialize(stream, source);
        stream.Seek(0, SeekOrigin.Begin);
        return (T)formatter.Deserialize(stream);
    }
}

My Confusions:

  1. Are there any other ways to do it?
  2. Which one is better and why?
  3. Does DataTable.Copy() internally uses DeepClone or some other logic?
like image 993
Nikhil Agrawal Avatar asked Oct 05 '12 07:10

Nikhil Agrawal


People also ask

How do I copy a DataTable?

Copy() creates a new DataTable with the same structure and data as the original DataTable. To copy the structure to a new DataTable, but not the data, use Clone().

What does DataTable clone do?

Clone creates a new DataTable with the same structure as the original DataTable, but does not copy any data (the new DataTable will not contain any DataRows ). To copy both the structure and data into a new DataTable, use Copy.


1 Answers

DataTable.Copy() itself creates a deep copy of the datatable, I am not talking about the implementation of DataTable.Copy() but the way copied data table works it is same as if the data is copied using DeepClone i.e. changes made to the data of one table does not affect the other.

So in your case you can simply use :-

DataTable dtCopy = dt.Copy();

OR you can also use :-

DataTable dtCopy = dt.Clone();
dtCopy.Merge(dt);
like image 146
Yatharth Varshney Avatar answered Oct 10 '22 01:10

Yatharth Varshney