Originally posted by kjewell23
I'm sorry I glanced over this question before.
First of all, a function returns something and a sub does not.
To call a sub or function (a method) from anywhere else in code you simply type its name.
For example say I have a sub called mySub:
[code=vbnet]
Private Sub mySub()
'do something
End Sub
[/code]
And say I want to call this sub from my button click Sub...all I would do is:
[code=vbnet]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArg s) Handles Me.Load
mySub()
End Sub
[/code]
If I were to call a Function on the other hand, I'd need to store it's output somewhere. So I need to create a variable in the button click Sub that matches the type that the Function returns and then call the Function...
For Example:
[code=vbnet]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArg s) Handles Me.Load
Dim myNumber As Integer = myFunction()
'myNumber will be set to 12 after the above line is executed.
'the number 12 is returned to this sub by the MyFunction function and is stored in the myNumber Integer.
End Sub
Private Function MyFunction() As Integer 'The "As Integer" portion of this line indicates what type of value is expected to be returned.
'This function returns an Integer value
Return 12
End Function
[/code]
One other thing about Subs and Functions is that you can pass values into them using parameters. Parameters are passed into Subs or Functions through the () part of the Sub or Function..
Private Function MyFunction(ByVal x As Integer) As Integer
(the bolded part is where the parameter is passed in)
A parameter is simply a variable passed into a Sub or Function that is used for some sort of processing within that function....
[code=vbnet]
Private Function MyFunction((ByV al x As Integer) As Integer
'x is a parameter passed into this function.
'in this case an Integer is expected to be passed into this function
'x can then be used to do whatever with....
'I'm going to subtract x from 12 and return that value
Return 12 - x
End Function
[/code]
This is an example of calling a function that expects a paramter:
[code=vbnet]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArg s) Handles Me.Load
Dim myNumber As Integer = MyFunction(3)
'In this case myNumber will be set to 9.....
End Sub
Private Function MyFunction((ByV al x As Integer) As Integer
'x is a parameter passed into this function.
'in this case an Integer is expected to be passed into this function
'x can then be used to do whatever with....
'I'm going to subtract x from 12 and return that value
Return 12 - x
End Function
[/code]
Does this make sense?
Comment