Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
7 Oct 2015 1  
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 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";

//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 cloned with only the structure of the MasterTable to CloneTable.

In short:

  • Copy() - For both structure and data
  • Clone() - For only structure

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here