string.Copy MethodUse the string.Copy method to copy the entire data from a string. Learn when string.Copy is needed.
This page was last reviewed on Apr 27, 2023.
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.
String CopyTo
Not often useful. Copy is not often useful but helps with string interning. We can test the result of string.Copy with object.ReferenceEquals.
An example. The string.Copy method is found on the System.String type. It internally calls into unsafe code that allocates and copies strings.
Step 1 Two string variables are assigned to a string literal, and to the result of string.Copy.
Step 2 We print the contents of the two strings, which are equal. Both have the value "Literal."
Step 3 The object data is equivalent in both objects, but the data is not in the same storage location and the references are unequal.
Tip This shows whether the 2 strings point to the same object data. It does not indicate if the object data is equal or not.
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
Internals. The string.Copy method first checks for null arguments. It enters an unsafe context which calls the internal wstrcpyPtrAligned method.
Detail This method copies the bytes and characters from one string to another.
And The loop in this method is highly optimized and unrolled. It would be hard to develop a faster one.
Assignment versus copy. In the C# language the assignment operator is guaranteed to do a bitwise copy of the storage location of the variable.
Also There are no user-defined overloads of the assignment operator in the C# language.
So Assigning a string variable to another variable is much faster than invoking string.Copy.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 27, 2023 (edit).
© 2007-2024 Sam Allen.