Assignment

In Visual Basic .NET, assignment statements are of the form:

variable, 
field, or 
property = 
expression

Either the type of the expression must be the same as that of the item receiving the assignment, or there must exist an appropriate implicit or explicit conversion from the type of the expression to the type of the item receiving the assignment. For information on implicit and explicit conversions, see Section 2.5.5 earlier in this chapter.

When an assignment is made to a value type, the value of the expression is copied to the target. In contrast, when an assignment is made to a reference type, a reference to the value is stored in the target. This is an important distinction that is worth understanding well. Consider the code in Example 2-3.

Example 2-3. Value-type assignment versus reference-type assignment

Public Structure SomeStructure Public MyPublicMember As String End Structure Public Class SomeClass Public MyPublicMember As String End Class Public Class AssignmentTest Public Shared Sub TestValueAndReferenceAssignment( ) Dim a, b As SomeStructure Dim c, d As SomeClass ' Test assignment to value type. a.MyPublicMember = "To be copied to 'b'" b = a a.MyPublicMember = "New value for 'a'" Console.WriteLine("The value of b.MyPublicMember is """ _ & b.MyPublicMember & """") ' Test assignment to reference type. c = New SomeClass( ) c.MyPublicMember = "To be copied to 'd'" d = c c.MyPublicMember = "New value for 'c'" Console.WriteLine("The value of d.MyPublicMember is ...

Get Programming Visual Basic .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.