C# String Clone Method

In c#, the string Clone method is used to clone and return a copy of the specified string object. The return value of the clone method is not an independent copy of the specified string because the clone method will return an existing string instance.

 

Following is the pictorial representation of using the string Clone() method to create and return a copy of the string object in the c# programming language.

 

C# String Clone Method Representation Diagram

 

If you observe the above diagram, we defined a string called “Welcome to Tutlane” and by using the string clone() method we cloned and returned a specified string as a result.

C# String Clone Method Syntax

Following is the syntax of defining a string Clone method to clone and return a copy of the string object in the c# programming language.

 

public object Clone()

If you observe syntax, the clone method will return an instance of a specified string as an object, and it won’t accept any parameters.

C# String Clone Method Example

Following is the example of using a string Clone() method to clone a specified string object and return a copy of the same data in the c# programming language.

 

using System;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          string msg = "Welcome to Tutlane";
          string msg1 = (string)msg.Clone();
          Console.WriteLine("String: {0}", msg);
          Console.WriteLine("Clone String: {0}", msg1);
          Console.WriteLine("Reference Equals: {0}", Object.ReferenceEquals(msg, msg1));
          Console.WriteLine("\nPress Enter Key to Exit..");
          Console.ReadLine();
       }
    }
}

If you observe the above example, we used a string Clone() method to clone a specified string and return an instance of specified string as a result.

 

Here we used a ReferenceEquals method to check whether the original and cloned string objects are referring to the same instance or not.

 

When you execute the above c# program, you will get the result as shown below.

 

C# String Clone Method Example Result

 

If you observe the above result, the string Clone() method has cloned the given string and returned the copy of the same string object.

 

This is how we can use Clone() method in the c# programming language based on our requirements.