How to use C# string Clone

The Clone() method serves as crucial functionality that facilitates the creation and acquisition of a duplicate instance of a string object. By invoking this method, a new string object is generated, mirroring the content and properties of the original string. This newly created string object is an independent entity, distinct from the source string, yet bearing an identical textual representation.

Object String.Clone()

Returns:

Object : Return the instance of the String

Clone() method

The Clone() method holds a unique attribute. It not only creates a copy of the string object but also grants access to a reference of the very instance from which the cloning operation was invoked. This reference provides a means to interact with and manipulate the original string object directly, even after the cloning process has taken place. Thus, the Clone() method ensures both the creation of a replica and the retention of a reference to the source string, allowing developers to employ and modify either entity as needed within their codebase.

Full Source C#
using System; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { { string str = "Clone() Test"; string clonedString = null; clonedString = (String)str.Clone(); MessageBox.Show (clonedString); } } } }

When you run this C# program you will get the same content of the first string "Clone() Test"

Conclusion

Using the Clone() method in CSharp, programmers can effectively manage and manipulate string objects, using the power of duplication and reference access to cater to their specific requirements and desired outcomes.