Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
4.93/5 (21 votes)
7 Oct 2015CPOL 185.7K   9   5
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.

C#
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.

C#
//Creating another DataTable to copy
DataTable dt_copy = new DataTable();
dt.TableName = "CopyTable";
dt_copy = dt.Copy();

Result:

Image 1

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.

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

Result:

Image 2

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
This article was originally posted at http://asp-arka.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer PwC
India India
I am a Software developer having an experience of 5 years in application development. To get me you can mail me at arkadeepde@gmail.com or you can visit my blog at ASP With Arka

Comments and Discussions

 
QuestionDatatable naming. Pin
Member 1282942013-Aug-18 5:23
Member 1282942013-Aug-18 5:23 
QuestionThanks Pin
Abdul Amin Khan16-Dec-17 23:31
Abdul Amin Khan16-Dec-17 23:31 
PraiseRe: Thanks Pin
Arkadeep De9-Jan-18 6:00
professionalArkadeep De9-Jan-18 6:00 
QuestionNew? Pin
Big Brother Don't Watch Me30-Sep-16 0:29
Big Brother Don't Watch Me30-Sep-16 0:29 
GeneralRe: New? Pin
Rajib1317-Oct-16 17:40
Rajib1317-Oct-16 17:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.