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:
DataTable.Copy()
internally uses DeepClone
or some other
logic?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().
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With