In visual basic, the string Clone method is useful to clone and return a copy of the specified string object. The return value of the clone method is not an independent copy of the specified string because the clone method will simply return an existing string instance.
Following is the pictorial representation of using the string Clone() method to create and return a copy of string object in a visual basic programming language.
If you observe the above diagram, we defined a string called “Welcome to Tutlane” and by using the string Clone() method we cloned and returned a specified string as a result.
Following is the syntax of defining a string Clone method to clone and return a copy of string object in a visual basic programming language.
Public Function Clone() As Object
If you observe the above syntax, the clone method will return an instance of the specified string as an object and it won’t accept any parameters.
Following is the example of using a string Clone() method to clone a specified string object and return a copy of the same data in a visual basic programming language.
Module Module1
Sub Main()
Dim msg As String = "Welcome to Tutlane"
Dim msg1 As String = CStr(msg.Clone())
Console.WriteLine("String: {0}", msg)
Console.WriteLine("Clone String: {0}", msg1)
Console.WriteLine("Reference Equals: {0}", Object.ReferenceEquals(msg, msg1))
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, we used a string Clone() method to clone the specified string and return an instance of the specified string as a result.
Here, we used the ReferenceEquals method to check whether the original and cloned string objects are referring to the same instance or not.
When we execute the above visual basic program, we will get the result as shown below.
If you observe the above result, the string Clone() method has cloned the given string and returned the copy of the same string object.
This is how we can use Clone() method in a visual basic programming language based on our requirements.