Visual Basic String Copy Method

In visual basic, the string Copy method is useful to create a new instance of string object with the same content of the specified string object. The copy method will return a string object that has the same value as the original string but it represents a new object reference.

 

The main difference between string Clone() and Copy() method is, the Copy method will create a new instance for the specified string object with the same content but the clone method will not create a new instance instead, it will refer an existing instance of the specified string object.

 

Following is the pictorial representation of using the string Copy() method to create a new string object with the same content in a visual basic programming language.

 

Visual Basic String Copy Method Representation Diagram

 

If you observe the above diagram, we defined a string called “Welcome to Tutlane” and by using the string Copy() method we created a new string object with the same content of the specified string object.

Visual Basic String Copy Method Syntax

Following is the syntax of defining a string Copy method to clone and return a copy of string object in a visual basic programming language.

 

Public Shared Function Copy(ByVal str As String) As String

If you observe the above syntax, the Copy method will create and return a new instance of a string with the same content of the specified string object. It will take a string as a parameter to create a copy of the specified string.

Visual Basic String Copy Method Example

Following is the example of using a string Copy() method to create a new string object with the same content of the specified string in a visual basic programming language.

 

Module Module1

    Sub Main()

        Dim msg As String = "Welcome to Tutlane"

        Dim msg1 As String = String.Copy(msg)

        Console.WriteLine("String: {0}", msg)

        Console.WriteLine("Copy 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 Copy() method to create a new string object with the content of the specified string object.

 

Here, we used the ReferenceEquals method to check whether the original and copy method 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.

 

Visual Basic (VB) String Copy Method Example Result

 

If you observe the above result, the string Copy() method has returned the copy of the same string object.

 

This is how we can use the Copy() method in a visual basic programming language based on our requirements.