How to use string Clone() and Copy() in C#

The string clone() and copy() both method are used to copy purpose.

Clone() – The Clone() method used to copy the structure of the actual data, or we can say copy the reference of the instance of string.
– If we use clone() method for copy DataTable then it returns the copy of structure of all DataTable, but it doesn’t contain any DataRows.

Copy() – The Copy() method create a same new string object with the same content. The Copy() method in c# used to copy the structure of data as well as actual data.
– If we use copy() method for copy DataTable then it returns the copy of structure of all DataTable with same set of  DataRows as original table.

Example of Clone() method in C#

    protected void Page_Load(object sender, EventArgs e)
string str = “Example of Clone() Method”;
string strclone = null;
strclone = (String)str.Clone();
Label1.Text = strclone;

Clone() method in VB.Net Code

 Dim str As String = “Example of Clone() Method”
Dim strclone As String = Nothing
strclone = CType(str.Clone(), String)
Label1.Text = strclone


Example of Copy() method in C#

 string str1 = null;
string str2 = null;

str1 = “Example of Copy() Method”;
str2 = string.Copy(str1);
Label1.Text = str2;

Copy() method in VB.Net

 Dim str1 As String = Nothing
Dim str2 As String = Nothing

str1 = “Example of Copy() Method”
str2 = String.Copy(str1)
Label1.Text = str2

In above copy() method example when we run the program we get same string result in str2 and str1.

Leave a Reply

Your email address will not be published. Required fields are marked *