Sub vs function

  • Thread starter Thread starter David A. Osborn
  • Start date Start date
A Function can return a value from itself. For example

Public Function Sum(ByVal a As Integer, _
ByVal b As Integer) As Integer
Return a + b
End Function

Then you can use this Function as follows

Dim result As Integer = Sum(2, 4)

On the other hand a Sub can not return a value from itself. It must use a
ByRef parameter to get a result. For example

Public Sub SumSub(ByVal a As Integer, _
ByVal b As Integer) As Integer)
Dim theSum As Integer = a + b
End Sub

This has no way of returning the result and using this like

Dim answer As Integer = SumSub(2, 4)

will generate a complile time error.

We can alter SumSub to take a ByRef parameter.
Public Sub SumSubByRef(ByVal a As Integer, _
ByVal b As Integer) As Integer, ByRef theSum As Integer)
theSum = a + b
End Sub

Then we can do the following

Dim answer As Integer
SumSubByRef(2, 4, answer)

This will get the sum placed into the variable answer.

As you can see, if you are going to be returning a value from your procedure
it is better to write it as a Function rather than a Sub.

Robby
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top