C# String Copy Method

In c#, the string Copy method is useful to create a new instance of a string object with the same content as the specified string object. The copy method will return a string object that has the same value as the original string, but it represents a new object reference.

 

The main difference between the string clone() and copy() method is, the copy method will create a new instance of a specified string object with the same content, but the clone method will not create a new instance; instead, it will refer to an existing instance of the specified string object.

 

Following is the pictorial representation of using the string Copy() method to create a new string object with the same content in the c# programming language.

 

C# String Copy Method Representation Diagram

 

If you observe the above diagram, we defined a string called “Welcome to Tutlane” and using a string copy() method, We created a new string object with the same content of the specified string object.

C# String Copy Method Syntax

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

 

public static string Copy(string str)

If you observe syntax, the copy method will create and return a new instance of the string with the same content of specified string objects. It takes a string as a parameter to create a copy of the specified string.

C# String Copy Method Example

Following is the example of using a string Copy() method to create a new string object with the same content of specified string in the c# programming language.

 

using System;

namespace Tutlane
{
    class Program
    {
        static void Main(string[] args)
        {
            string msg = "Welcome to Tutlane";
            string msg1 = string.Copy(msg);
            Console.WriteLine("String: {0}", msg);
            Console.WriteLine("Copy 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 Copy() method to create a new string object with the content of the specified string object.

 

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

 

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

 

C# String Copy Method Example Result

 

If you observe the above result, the string Copy() method has returned the copy of the same string object.

 

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