C# string.Copy Method

Use the string.Copy method to copy a string's entire data. Learn when string.Copy is needed.


The string.Copy method copies string data. In this language, strings rarely need copying. But there are some cases where they do.StringsCopyTo

Not often useful.

Copy is not often useful but helps with string interning. We can test the result of string.Copy with object.ReferenceEquals.string.Intern

An example.

The string.Copy method is found on the System.String type. It internally calls into unsafe code that allocates and copies strings.

Variables: Two string variables are assigned to a string literal, and to the result of string.Copy.


Alias: The string.Copy method is aliased to the System.String.Copy method, and it accepts one parameter of type string.

Info: The object data is equivalent in both objects, but the data is not in the same storage location and the references are unequal.

ReferenceEquals: This shows whether the 2 strings point to the same object data. It does not indicate if the object data is equal or not.

C# program that uses Copy string using System; class Program { static void Main() { // // Copy a literal string. // string value1 = "Literal"; string value2 = string.Copy(value1); // // Write the string values. // Console.WriteLine(value1); Console.WriteLine(value2); // // See if the references are equal. // Console.WriteLine(object.ReferenceEquals(value1, value2)); } } Output Literal Literal False


The string.Copy method first checks for null arguments. It enters an unsafe context which calls the internal wstrcpyPtrAligned method.

Copies: 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
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen,