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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 27, 2023 (edit).