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).