TravelinMax
TravelinMax

Reputation: 65

Why can I manipulate a variable in my subroutine without passing it as a parameter?

I am starting my VB.NET class this semester and it has been a while since I have done anything in VB.NET and I am realizing I have forgotten some of the basics. In the following example program, I do not need to pass exampleVar to the function to be able to change the value. Why is this and what am I doing wrong?

Public Class Form1
    Dim exampleVar As Integer = 0


    Sub MySub()
        exampleVar = 123
    End Sub


    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        MySub()
        TextBox1.Text = exampleVar
    End Sub
End Class

The textbox displays the value 123

Upvotes: 0

Views: 74

Answers (3)

ttrmw
ttrmw

Reputation: 161

So in your example the variable declaration is inside the 'scope' of the class. That makes it accessible to anything else that is also inside the scope of the class.

If the declaration took place inside MySub(), eg:

Public Sub MySub()
    Dim exampleVar As Integer = 0
    exampleVar = 123
End Sub 

it would be inaccessible outside of the scope of MySub, at which point you might have to start passing it around, but remember in general that if you do this, you will mostly be passing 'ByVal' or, by value. That means that:

Public Sub MySub(ByVal arg As Integer) 
    arg = 123
End Sub 

Will not affect the original variable when this method is called like:

Dim exampleVar As Integer = 0 
...
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    MySub(exampleVar)
    TextBox1.Text = exampleVar
End Sub

In this example, exampleVar would still be 0 - which I think is the effect you were expecting.

When objects are passed ByVal, their value is passed in, but not the original object. To affect the original variable in this manner, you might use ByRef, which passes in the object 'by reference'.

Upvotes: 0

chris_techno25
chris_techno25

Reputation: 2477

First off...

Dim exampleVar As Integer = 0

The code above is declared just 1 level below your Class Form1, which means, it's a Global variable that any of the subs below the Class Form1 can access and use.

Sub MySub()
    exampleVar = 123
End Sub

The code above is a Sub that sets exampleVar to 123.

Lastly... When your form loads, you call the Sub that equates exampleVar to 123, after which, TextBox1.Text is equated to whatever value exampleVar holds, which is 123, thus it's displaying 123.

You're are doing nothing wrong if that is what you want. If you don't want to set exampleVar to 123, remove the MySub() from the Form_Load event.

Upvotes: 1

Usman Farooq
Usman Farooq

Reputation: 161

exampleVar is global variable with value is equal to 0. You are updating it in MySub() method before displaying it.

Upvotes: 0

Related Questions