This lesson is part of an ongoing tutorial. The first part is here: Create your own Subs in VB .NET
In the previous section, you learned how to set up a simple function. Let's set up another Function, as a further example. This time we'll add some Parameters to our Function. You use the Parameters in exactly the same way as you did for a Sub.
- So add another button to your Form
- Set its Text property to Get Function Answer
- Add two Textboxes to your Form
- Set the Name Property of the first Textbox to txtNumber1
- Set the Name Property of the second Textbox to txtNumber2
- Set up the following Function in your code window (The first line might be spread over two lines here. You can keep yours on one line.)
Private Function AddTwoNumbers(first As Integer, second As Integer) As Integer
Dim answer As Integer
answer = first + second
AddTwoNumbers = answer
So the name of this Function is AddTwoNumbers, and we've set it up to return an Integer value. The two parameters we're passing in are also Integers. The code inside the Function simply adds up whatever is inside the variables first and second. The result is passed to another variable, answer. We then pass whatever is inside answer to the name of our Function. So AddTwoNumbers will be equal to whatever is in the variable answer.
Instead of saying AddTwoNumbers = answer you can use the Return keyword. You use it like this:
The result is the same: the value inside the variable answer is now the value of the function.
Open up the code for your "Get Answer" button, and add the following code to it:
Dim first As Integer
Dim second As Integer
Dim result As Integer
first = Val(txtNumber1.Text)
second = Val(txtNumber2.Text)
result = AddTwoNumbers(first, second)
If result = 0 Then
MessageBox.Show("Please try again ")
MessageBox.Show("The answer is " & result)
So we're telling Visual Basic to execute our Function on this line:
result = AddTwoNumbers( first, second )
We're saying, "Run the Function called AddTwoNumbers. Hand it the values from the two variables. When you've finished running the function, pass whatever the value of AddTwoNumbers is to the variable called result."
The next few lines are just testing what is inside the variable result. Remember: the variable result will hold whatever the value of AddTwoNumbers was.
When you've finished typing your code, run your programme and test it out. Type a number in the first text box, and one in the other. Then click the "Get Function Answer" button. Try typing two zeros into the textboxes and see what happens.
Setting up and using functions can be quite tricky at first, but it's well worth your while persevering: they can vastly improve your coding skills.
In the next section, we explain what a Standard Module is, and how to create your own.