C# | How to copy a String into another String
Last Updated :
01 Feb, 2019
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:
using System;
class GFG {
static public void Main()
{
string strA = "GeeksforGeeks" ;
string strB = String.Copy(strA);
Console.WriteLine( "Original String strA: {0}" , strA);
Console.WriteLine( "Copied String strB: {0}" , strB);
}
}
|
Output:
Original String strA: GeeksforGeeks
Copied String strB: GeeksforGeeks
Example 2:
using System;
class GFG {
static public void Main()
{
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:" );
strB = String.Copy(strA);
Console.WriteLine( "Value of string A: {0}" , strA);
Console.WriteLine( "Value of string B: {0}" , strB);
Console.WriteLine( "Is reference of strings is equal : {0}" ,
Object.ReferenceEquals(strA, strB));
}
}
|
Output:
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:
Share your thoughts in the comments
Please Login to comment...