What's the use of System.String.Copy in .NET?

Solution 1:

With String.Copy you are actually allocating new memory and copying the characters from one string to another; you get a completely new instance as opposed to having both variables being the same instance. This may matter if you use the string with unmanaged code which deals with the memory locations directly and can mutate the string.

Solution 2:

Here's one piece of the puzzle. It doesn't explain why you would want to do it, but it does help explain a functional difference.

If you pin the string using the fixed keyword, the contents would be mutable. Off the top of my head, I can't think of a situation in which you would want to do this, but it is possible.

string original = "Hello World";
string refCopy = original;
string deepCopy = String.Copy(original);

fixed(char* pStr = original)
{
   *pStr = 'J';
}

Console.WriteLine(original);
Console.WriteLine(refCopy);
Console.WriteLine(deepCopy);

Output:

Jello World
Jello World
Hello World

Solution 3:

String.Copy returns a new String and does not yield the same results as

String copy = otherString;

Try this:

using System;

class Program
{
    static void Main()
    {
        String test = "test";
        String test2 = test;
        String test3 = String.Copy(test);

        Console.WriteLine(Object.ReferenceEquals(test, test2));
        Console.WriteLine(Object.ReferenceEquals(test, test3));

        Console.ReadLine();
    }
}

When you set test2 = test these references point to the same String. The Copy function returns a new String reference that has the same contents but as a different object on the heap.


Edit: There are a lot of folks that are pretty upset that I did not answer the OP's question. I believe that I did answer the question by correcting an incorrect premise in the question itself. Here is an analogous (if not oversimplified) question and answer that will hopefully illustrate my point:

Question:

I have observed that my car has two doors, one on each side of the car. I believe it to be true that regardless of which door I use I will end up sitting in the driver's seat. What is the purpose of the other door?

Answer:

Actually it is not true that if you use either door you will end up in the driver's seat. If you use the driver's side door you will end up in the driver's seat and if you use the passenger's side door you will end up in the passenger's seat.

Now in this example you could argue that the answer is not really an answer as the question was "what is the purpose of the passenger's side door?". But since that question was wholly based on a misconception of the how the doors worked does it not follow that the refutation of the premise will shed new light on the purpose of the other door by deduction?