C# string Copy method explanation with example

C# String Copy method:

Copy method is used to copy the content of a string and to create a new instance of String with the exact same value. You can’t use this method to create a mutable string. In this post, I will show you how to use Copy method with examples in C#.

Definition of String Copy:

Below is the definition of String Copy method:

public static string Copy(string str)

Here,

  • str is the original string to copy.
  • It returns a new string with the same value as the given string.

It throws ArgumentNullException if str is null.

Example of String Copy:

Let’s take a look at the below program:

using System;

public class Program {

	public static void Main(string[] args) {
		string givenString = "Hello World";
		string copyString = String.Copy(givenString);
		
		Console.WriteLine("Given String :"+givenString);
		Console.WriteLine("Copied String :"+copyString);
	}
}

Here,

  • givenString is the given string.
  • copyString is the copied string.
  • The last two WriteLine lines are used to print the values of these strings.

If you run this program, it will print the below output:

Given String :Hello World
Copied String :Hello World

As you can see here, both strings have the same values.

Difference between assignment operator:

There is a difference between the assignment operator and the Copy method. The Copy method returns a new string object with the same value. But, the assignment operator assigns an existing string reference.

Let’s try to understand this with an example.

using System;

public class Program {

	public static void Main(string[] args) {
		string givenString = "Hello World";
		string anotherString = "Hello World";
		string copyString = String.Copy(givenString);
		
		Console.WriteLine(Object.ReferenceEquals(givenString, anotherString));
		Console.WriteLine(Object.ReferenceEquals(givenString, copyString));
	}
}

Here,

  • givenString and anotherString both are assigned the same string value.
  • copyString is created by using the String.Copy method.
  • The last two WriteLines are using Object.ReferenceEquals to check if both objects are refering to the same string or not. The first one is checking givenString and anotherString. The second is is checking givenString and copyString string variables.

If you run this program, it will print the below output:

True
False

As you can see here, givenString and anotherString are refering to the same. But givenString and copyString are refering to different objects. Copy always creates a new instance.

You might also like: