C# String Copy Method

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

 

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

 

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

 

C# String Copy Method Representation Diagram

 

If you observe above diagram, we defined a string called “Welcome to Tutlane” and by using string copy() method we created a new string object with the same content of 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 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 string with the same content of specified string object. It takes a string as parameter to create a copy of specified string.

C# String Copy Method Example

Following is the example of using string Copy() method to create a new string object with the same content of specified string in 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 above example, we used a string Copy() method to create a new string object with the content of specified string object.

 

Here we used a ReferenceEquals method to check whether the original and copy method 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 Copy Method Example Result

 

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

 

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