Copy Method

String.Copy Method (String)

 

Creates a new instance of String with the same value as a specified String.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

Public Shared Function Copy (
	str As String
) As String

Parameters

str
Type: System.String

The string to copy.

Return Value

Type: System.String

A new string with the same value as str.

Exception Condition
ArgumentNullException

str is null.

TheCopy method returns a String object that has the same value as the original string but represents a different object reference. It differs from an assignment operation, which assigns an existing string reference to an additional object variable. The example illustrates the difference.

The following example creates two string objects with different values. When it calls the Copy method to assign the first value to the second string, the output indicates that the strings represent different object references although their values are now equal. On the other hand, when the first string is assigned to the second string, the two strings have identical values because they represent the same object reference.

Module Example
   Public Sub Main()
      Dim str1 As String = "abc"
      Dim str2 As String = "xyz"

      Console.WriteLine("str1 = '{0}'", str1)
      Console.WriteLine("str2 = '{0}'", str2)
      Console.WriteLine()

      Console.WriteLine("After String.Copy...")
      str2 = String.Copy(str1)
      Console.WriteLine("str1 = '{0}'", str1)
      Console.WriteLine("str2 = '{0}'", str2)
      Console.WriteLine("ReferenceEquals: {0}", Object.ReferenceEquals(str1, str2))
      Console.WriteLine("Equals: {0}", Object.Equals(str1, str2))
      Console.WriteLine()

      Console.WriteLine("After Assignment...")
      str2 = str1
      Console.WriteLine("str1 = '{0}'", str1)
      Console.WriteLine("str2 = '{0}'", str2)
      Console.WriteLine("ReferenceEquals: {0}", Object.ReferenceEquals(str1, str2))
      Console.WriteLine("Equals: {0}", Object.Equals(str1, str2))
   End Sub
End Module
' The example displays the following output:
'       str1 = 'abc'
'       str2 = 'xyz'
'       
'       After String.Copy...
'       str1 = 'abc'
'       str2 = 'abc'
'       ReferenceEquals: False
'       Equals: True
'       
'       After Assignment...
'       str1 = 'abc'
'       str2 = 'abc'
'       ReferenceEquals: True
'       Equals: True

.NET Framework
Available since 1.1
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Return to top
Show:
© 2016 Microsoft