Sub Procedure is same as procedure in C#. Sub procedure does not return any value.That is the only difference between the function and the sub procedure.While doing programming in console in visual studio directly it opens with sub procedure.The following is a syntax to sub procedure.
[vbnet]
[AccessModifiers] Sub SubName [(AttributeList)]
[Statements]
End Sub[/vbnet]
The following table shows the description about the above syntax.
Parts
Description
Access Modifiers
Used to provide access permissions for the sub procedures. Example: public, private..etc
SubName
Used to Indicate the name of the Sub
Attribute ParameterList
Used to Declare the list of the parameter
Ways to Pass Parameters to Sub Procedure
Description
Passing parameters mean we have to send the values to the sub procedure in order to perform the action. We can pass the values in two different ways as follows.
Passing parameters by Value
Passing parameters by Reference
Passing parameters by Value:
If we are using passing parameters by value method, then we have to declare that parameter with the ByValue datatype in the sub procedure. We have to use this By Value method when the value of the parameter does not need to change. The following code shows you the syntax for the By Value mechanism.
[vbnet]
Sub SubName(ByVal parameter_name as datatype)
[Statements]
End Sub
[/vbnet]
Passing parameters by Reference:
If we are using passing parameters by the reference method, then we have to declare that parameter with the ByRef datatype in the sub procedure. We have to use this By Reference method when the value of the parameter needs to change during its calling. The following code shows you the syntax for the By Value mechanism.
[vbnet]
Sub SubName(ByRef parameter_name2)
parameter=value
End Sub
Dim parameter_Name1
parameter_Name= Value
SubName parameter_Name1
[/vbnet]
Example
Following is an example which describes how to pass parameters.
[vbnet]Module Module1
Sub Calculate(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
Calculate(25, 10)
Calculate(40, 20)
Calculate(30, 27.5)
Console.ReadLine()
End Sub
End Module[/vbnet]
Output:
Following is an result regarding the above code.
Summary
Points
ByValue is a datatype that given value will not be changed.
ByRef is a datatype that given value will be changed.