How to clone a string in C#

Overview

Strings in C# can be cloned, and you can use the Clone() method for this purpose. It is a method of the String class. When used on a string, it returns the copy of the string. The returned value is a reference of that exact string or string data.

Syntax

The syntax of the clone function is as follows:

public object Clone()

Parameter

None. The Clone() method accepts no parameters.

Return value

The value returned is a reference of the cloned string.

Code example

In the code below, we created strings and we cloned them using the Clone() method.

using System;
// Our Class
class StringCloning
{
// main method
static void Main()
{
// initialize and create strings
string username = "Theodore Onyejiaku";
string role = "Software Developer";
string nickname = "KC";
// explicit type conversion and cloning
string u = (String)username.Clone();
string r = (String)role.Clone();
string n = (String)nickname.Clone();
// print cloned values to the console
System.Console.WriteLine(u);
System.Console.WriteLine(r);
System.Console.WriteLine(n);
}
}

In the code above, we defined and initialized our string variables. From line 9 to 11, we explicitly converted the strings and were able to call the Clone() method.