What is the difference between String.Copy() and String.Clone() methods in C#?


The String.Copy() method creates a new instance of String. This is same as the specified String.

The following is an example of Copy() method −

Example

 Live Demo

using System;
class Demo {
   static void Main(String[] args) {

      string str1 = "mark";
      string str2 = "marcus";

      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);

      Console.WriteLine("After using String.Copy...");
      str2 = String.Copy(str1);

      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);
   }
}

Output

str1 = 'mark'
str2 = 'marcus'
After using String.Copy...
str1 = 'mark'
str2 = 'mark'

The String.Clone() method returns a reference to the instance of String. The following is an example of Clone() method −

Example

 Live Demo

using System;
class Demo {
   static void Main(String[] args) {
     
      string str1 = "amy";
      string str2 = "emma";

      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);

      Console.WriteLine("After using String.Clone...");
      str2 = (String)str1.Clone();

      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);
   }
}

Output

str1 = 'amy'
str2 = 'emma'
After using String.Clone...
str1 = 'amy'
str2 = 'amy'

Updated on: 21-Jun-2020

350 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements