vb.net byval and byref

Pluralsight courses
LinkedIn Premium uses PayScale to estimate job salaries

Premium (Not Free) Video Tutorials

Free Video Tutorials & Free Tools

Original source: Homeandlearn.co.uk

The word ByVal is short for "By Value". What it means is that you are passing a copy of a variable to your Subroutine. You can make changes to the copy and the original will not be altered.

ByRef is the alternative. This is short for By Reference. This means that you are not handing over a copy of the original variable but pointing to the original variable. Let's see a coding example.

Add a new button the form you created in the previous section. Double click the button and add the following code:

Dim Number1 As Integer

Number1 = 10
Call IncrementVariable(Number1)

MsgBox(Number1)

You'll get a wiggly line under IncrementVariable(Number1). To get rid of it, add the following Subroutine to your code:

Private Sub IncrementVariable(ByVal Number1 As Integer)
Number1 = Number1 + 1
End Sub

When you're done, run the programme and click your new button. What answer was displayed in the message box?

It should have been 10. But hold on. Didn't we increment the variable Number1 with this line?

Number1 = Number1 + 1

So Number1 started out having a value of 10. After our Sub got called, we added 1 to Number1. So we should have 11 in the message box, right?

The reason Number1 didn't get incremented was because we specified ByVal in the Sub:

ByVal Number1 As Integer

This means that only a copy of the original variable got passed over. When we incremented the variable, only the copy got 1 added to it. The original stayed the same – 10.

Change the parameter to the this:

ByRef Number1 As Integer

Run your programme again. Click the button and see what happens.

This time, you should see 11 displayed in the message box. The variable has now been incremented!

It was incremented because we used ByRef. We're referencing the original variable. So when we add 1 to it, the original will change.

The default is ByVal – which means a copy of the original variable. If you need to refer to the original variable, use ByRef.

Related posts:

  1. change windows wallpaper using vb.net Also see this video Want to change windows wallpaper using...
  2. Build a bluetooth Chat Application Bluetooth is one of today's most exciting technologies. It...
  3. objects and classes in vb.net This is a really great article for beginners who want...
  4. Subroutines and Functions Well I am writing this tutorial in which i wil...
  5. Learn vb.net in 24 hours Yes that's right you can actually learn vb.net in 24...

Related posts brought to you by Yet Another Related Posts Plugin.

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

Powered by WP Hashcash

This blog uses the cross-linker plugin developed by Web-Developers.Net