The difference between ByVal and ByRef in VB

Source: Internet
Author: User

What is the difference between ByVal and ByRef in VB? In short, ByVal is the value, ByRef is the address, ByVal: Indicates that the parameter is passed by value. ByRef: Indicates that the parameter is passed by reference. The following green Tea Small series for you to introduce the difference between ByVal and ByRef.

1. The reference parameter (ref) can be passed as a reference parameter in a function member invocation. Must have been definitely assigned, and the output parameter (out) must not be definitely assigned before it can be passed as an output parameter in a function member invocation, before the function member returns normally.

2. Within a function, reference parameters (ref) are considered initially assigned, and output parameters (out) are considered initially unassigned.

3, by default, all the parameters in VB are value transfer. A reference pass is only explicitly contained in the modifier of a parameter, out or ref. But what you need to know is that when the type of the argument is a reference type, you pass a reference to an object instead of the actual object.

Instance:

Sub Add1 (ByVal No as Int32)

no=no+100

End Sub

Sub Add2 (ByRef No as Int32)

no=no+100

End Sub

Private Sub Button1_Click (sender as object,e as EventArgs) Handles Button1.Click

Dim A As Int32

a=100

ADD1 (a)

MsgBox ("A" value is: "& A)" shows: A has a value of 100

ADD2 (a)

The value of MsgBox ("a": "& A") shows: A has a value of 200 because the parameter no in ADD2 is ByRef, that is,

' is delivered by address, so modifying the No in ADD2 will cause

The value of the ' source parameter a ' is also modified.

End Sub

ByVal is the Transfer value source data will not be modified, you can use this value as your own local variables; ByRef is the delivery address, the source data may be modified, your operation on this variable will affect the variable you pass in.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.