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 clone method is not an independent copy of specified string because the clone method will simple return an existing string instance.

 

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

 

C# String Clone Method Representation Diagram

 

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

C# String Clone Method Syntax

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

 

public object Clone()

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

C# String Clone Method Example

Following is the example of using string Clone() method to clone a specified string object and return a copy of same data in 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 above example, we used a string Clone() method to clone a specified string and return an instance of specified string as result.

 

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

 

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

 

C# String Clone Method Example Result

 

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

 

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