Introduction
In this post, we will discuss about the two major methods of DataTable
in C#. One is Copy()
and the other one is Clone()
. Though these two sound identical but there are huge differences between these two. Let's see what those are.
Description
There are two things to copy or clone of a DataTable
. These are structure and data. Copy
and Clone
are playing with these two.
Let us create a DataTable
first.
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Email");
dt.TableName = "MasterTable";
dt.Rows.Add("1", "Arka", "arka@gmail.com");
dt.Rows.Add("2", "Anusua", "anu@gmail.com");
dt.Rows.Add("3", "Sayantani", "sayantani@gmail.com");
DataTable.Copy()
DataTable.Copy()
returns a DataTable
with the structure and data of the DataTable
.
DataTable dt_copy = new DataTable();
dt.TableName = "CopyTable";
dt_copy = dt.Copy();
Result:
As here, you can see the DataTable dt
is being copied with the data and structure to CopyTable
.
DataTable.Clone()
Unlike Copy()
, DataTable.Clone()
only returns the structure of the DataTable
, not the rows or data of the DataTable
.
DataTable dt_clone = new DataTable();
dt.TableName = "CloneTable";
dt_clone = dt.Clone();
Result:
As here you can see DataTable dt
is being cloned with only the structure of the MasterTable
to CloneTable
.
In short:
Copy()
- For both structure and data
Clone()
- For only structureCodeProject