Difference between Sub and Function in Visual Basic and VB.Net
What's the difference between a Sub and a Function in Visual Basic ?
re: Difference between Sub and Function in Visual Basic and VB.Net
A Function can return a value from itself. For example
Code:
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
Code:
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.
Sub Vs Function in Visual Basic
The Sub statement is used to execute one or more lines of code, period.
The Function statement is used to execute one or more lines of code AND return a value to the caller.
Use a Sub when you do not need to return a value to the calling code. Use a Function when you need to return a value.
Sub and Function in Visual Basic.Net
To learn more about Visual Basic.NET Sub and Function statements click these links:
Sub
Function