Sunday, October 4, 2015

DataTable.Copy() Vs. DataTable.Clone() in C#

Introduction:

In this post we will discuss about the two major methods of DataTable in C#. One is Copy() and another one is Clone(). Though these two are sounds identical but there are huge difference between these two. Lets see what are those..

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.

Lets us create a DataTable first.

DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Email");
dt.TableName = "MasterTable";
//insert into DataTable
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.

//Creating another DataTable to copy
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.

//Creating another DataTable to clone
DataTable dt_clone = new DataTable();
dt.TableName = "CloneTable";
dt_clone = dt.Clone();

Result:

As here you can see DataTable dt is being clone with only the structure of the MasterTable to CloneTable.

In short:
Copy() - For both structure and data.
Clone() - For only structure.

1 comment:

Popular Posts

Pageviews