String.Copy
The C# string.Copy
method copies string
data. In this language, strings rarely need copying—but there are some cases where they do.
Copy is not often useful but helps with string
interning. We can test the result of string.Copy
with object.ReferenceEquals
.
The string.Copy
method is found on the System.String
type. It internally calls into unsafe code that allocates and copies strings.
string
variables are assigned to a string
literal, and to the result of string.Copy
.using System; // Step 1: copy a literal string. string value1 = "Literal"; string value2 = string.Copy(value1); // Step 2: write the string values. Console.WriteLine(value1); Console.WriteLine(value2); // Step 3: see if the references are equal. Console.WriteLine(object.ReferenceEquals(value1, value2));Literal Literal False
The string.Copy
method first checks for null
arguments. It enters an unsafe context which calls the internal wstrcpyPtrAligned
method.
string
to another.In the C# language the assignment operator is guaranteed to do a bitwise copy of the storage location of the variable.
string
variable to another variable is much faster than invoking string.Copy
.String.Copy
copies the internal data stored in the managed heap for the string
, but does not change the reference by assignment. The method copies the characters in the string.