1 out of 1 rated this helpful Rate this topic

ByVal (Visual Basic)

Updated: July 2011

Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code.

The following example demonstrates the use of the ByVal parameter passing mechanism with a reference type argument. In the example, the argument is c1, an instance of class Class1. ByVal prevents the code in the procedures from changing the underlying value of the reference argument, c1, but does not protect the accessible fields and properties of c1.


Module Module1

    Sub Main()

        ' Declare an instance of the class and assign a value to its field.
        Dim c1 As Class1 = New Class1()
        c1.Field = 5
        Console.WriteLine(c1.Field)
        ' Output: 5

        ' ByVal does not prevent changing the value of a field or property.
        ChangeFieldValue(c1)
        Console.WriteLine(c1.Field)
        ' Output: 500

        ' ByVal does prevent changing the value of c1 itself. 
        ChangeClassReference(c1)
        Console.WriteLine(c1.Field)
        ' Output: 500

        Console.ReadKey()
    End Sub

    Public Sub ChangeFieldValue(ByVal cls As Class1)
        cls.Field = 500
    End Sub

    Public Sub ChangeClassReference(ByVal cls As Class1)
        cls = New Class1()
        cls.Field = 1000
    End Sub

    Public Class Class1
        Public Field As Integer
    End Class

End Module


Date

History

Reason

July 2011

Changed the example to show the output.

Customer feedback.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
VS2010 SP1
There should be a note in here saying that by default, VS2010 SP1 will stop automatically adding the "ByVal" to method parameters. You can still add it manually if you wish to do so, but leaving it out causes no change in the default/existing behavior.