C# | How to copy a String into another String
String.Copy(String) Method is used to create a new instance of String with the same value as a specified String. In other words, this method is used to copy the data of one string into a new string.
The new string contains same data like an original string but represents a different object reference.
Syntax:
public static string Copy (string value);
Parameter: Here value is the string which is to be copied.
Return Value: The return type of this method is System.String. This method returns a new string that contains the data similar to the value.
Exception: This method will give ArgumentNullException if the value is null.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# program to illustrate Copy() Method using System; class GFG { // Main Method static public void Main() { // string which is to be copied string strA = "GeeksforGeeks" ; // Copy the data of strA string // into strB string // using Copy() method string strB = String.Copy(strA); Console.WriteLine( "Original String strA: {0}" , strA); Console.WriteLine( "Copied String strB: {0}" , strB); } } |
Original String strA: GeeksforGeeks Copied String strB: GeeksforGeeks
Example 2:
// C# program to check reference of strings using System; class GFG { // Main Method static public void Main() { // string string strA = "GeeksforGeeks" ; string strB = "C# Tutorials" ; Console.WriteLine( "Original string A: {0}" , strA); Console.WriteLine( "Original string B: {0}" , strB); Console.WriteLine(); Console.WriteLine( "After copy:" ); // copy the data of strA string // into strB string // using Copy() method strB = String.Copy(strA); Console.WriteLine( "Value of string A: {0}" , strA); Console.WriteLine( "Value of string B: {0}" , strB); // Checking the reference of both string Console.WriteLine( "Is reference of strings is equal : {0}" , Object.ReferenceEquals(strA, strB)); } } |
Original string A: GeeksforGeeks Original string B: C# Tutorials After copy: Value of string A: GeeksforGeeks Value of string B: GeeksforGeeks Is reference of strings is equal : False
Reference: