Open In App

C# | Copy() Method

Improve
Improve
Like Article
Like
Save
Share
Report

In C#, Copy() is a string method. It is used to create a new instance of String with the same value for a specified String. The Copy() method returns a String object, which is the same as the original string but represents a different object reference. To check its reference, use assignment operation, which assigns an existing string reference to an additional object variable.

Syntax:

public static string Copy(string str)

Explanation : This method accepts single parameter str which is the original string to be copied. And it returns the string value, which is the new string with the same value as str. The type of Copy() method is System.String.

Example Program to illustrate the Copy() Method




// C# program to demonstrate the 
// use of Copy() method
using System;
class Program {
      
    static void cpymethod()
    {
        string str1 = "GeeksforGeeks";
        string str2 = "GFG";
        Console.WriteLine("Original Strings are str1 = "
            + "'{0}' and str2='{1}'", str1, str2);
                  
        Console.WriteLine("");
  
        Console.WriteLine("After Copy method");
        Console.WriteLine("");
  
        // using the Copy method
        // to copy the value of str1 
        // into str2
        str2 = String.Copy(str1);
  
        Console.WriteLine("Strings are str1 = "
        +"'{0}' and str2='{1}'", str1, str2);
  
        // check the objects reference equal or not
        Console.WriteLine("ReferenceEquals: {0}",
            Object.ReferenceEquals(str1, str2));
  
        // check the objects are equal or not
        Console.WriteLine("Equals: {0}", Object.Equals(str1, str2));
        Console.WriteLine("");
  
        Console.WriteLine("After Assignment");
        Console.WriteLine("");
  
        // to str1 object reference assign to str2
        str2 = str1;
  
        Console.WriteLine("Strings are str1 = '{0}' "
                    +"and str2 = '{1}'", str1, str2);
  
        // check the objects reference equal or not
        Console.WriteLine("ReferenceEquals: {0}"
            Object.ReferenceEquals(str1, str2));
  
        // check the objects are equal or not
        Console.WriteLine("Equals: {0}", Object.Equals(str1, str2));
  
    }
      
    // Main Method
    public static void Main()
    {
          
        // calling method
        cpymethod();
    }
}


Output:

Original Strings are str1 = 'GeeksforGeeks' and str2='GFG'

After Copy method

Strings are str1 = 'GeeksforGeeks' and str2='GeeksforGeeks'
ReferenceEquals: False
Equals: True

After Assignment

Strings are str1 = 'GeeksforGeeks' and str2 = 'GeeksforGeeks'
ReferenceEquals: True
Equals: True

Reference : https://msdn.microsoft.com/en-us/library/system.string.copy



Last Updated : 21 Jun, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads