C# String.Clone() – Examples

String.Clone() method is used to get a reference to the given instance of String.

In this tutorial, we will learn about the syntax of C# String.Clone() method, and learn how to use this method with the help of examples.

Clone()

String.Clone() returns a reference to this instance of String.

ADVERTISEMENT

Syntax

The syntax of Clone() method is

String.Clone()

Return Value

This method returns an value of type Object. We may have to typecast it to String.

Example 1 – Clone()

In this example, we will take a string str and clone it using String.Clone() method.

C# Program

using System;
 
class Example {
    static void Main(string[] args) {
        String str = "abc";
        String result = (String) str.Clone();
        Console.WriteLine($"Original String is  : {str}");
        Console.WriteLine($"Cloned String is    : {result}");
    }
}

Output

Original String is  : abc
Cloned String is    : abc

Example 2 – Clone()

In this example, we will take a string str with null value, and clone it using String.Clone() method. Since the string is null, Clone() method throws System.NullReferenceException.

C# Program

using System;
 
class Example {
    static void Main(string[] args) {
        String str = null;
        String result = (String) str.Clone();
        Console.WriteLine($"Original String is  : {str}");
        Console.WriteLine($"Cloned String is    : {result}");
    }
}

Output

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Example.Main(String[] args) in D:\workspace\csharp\HelloWorld\Program.cs:line 6

Conclusion

In this C# Tutorial, we have learnt the syntax of C# String.Clone() method, and also learnt how to use this method with the help of C# example programs.