How to copy string value to another string in C# using Copy()

Overview

In C#, Copy() is a string method that is used to create a new string with the same value as the one it is copied from.

What this means is that when you call the Copy() method on a certain string, a copy of the value of this string is returned. You can then assign this returned string value to a variable or perform any other operations with it.

Syntax

string.Copy(stringToCopy)

Parameters

stringToCopy: This is the string whose value you want to copy.

Return value

The value returned is a string that is the same as the value of the string that was copied.

Code example

In the code snippet below, we created several strings and called the Copy() method on each one of them. Then we printed the copied values of the strings to the console.

// create class
class CopyString
{
// main method
static void Main()
{
// initialize strings
string name = "Theodore";
string role = "Software Developer";
string bestHubby = "Guitarist";
// Copy strings above with
// the Copy() method
string n = string.Copy(name);
string r = string.Copy(role);
string b = string.Copy(bestHubby);
// print out copied string values
System.Console.WriteLine(n);
System.Console.WriteLine(r);
System.Console.WriteLine(b);
}
}

We can see from the output of the code snippet above that the strings were successfully copied.