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:
- C# program to find the sum of all odd numbers below a given number
- C# program to print from 1 to 10 in different ways
- C# program to iterate over the characters of a string
- C# program to find the sum of odd and even numbers in an array
- C# program to get the substring of a string
- C# string Join method explanation with example