Subroutines in Visual Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes Subroutines in Visual Basic .NET
By definition, a Visual Basic Soubroutine is chunk of code enclosed by the Sub and End Sub.
It performs a task for the code that invokes it and unlike the Function does not return a value.
Its syntax is as follows:
[ accessibility ] Sub routine_name [ paramaters ] statements End SubThe accessibility can be Public, Protected, Friend, Protected Friend, or Private and determines which pieces of code can invoke the subroutine.
The name of the subroutine must be a valid Visual Basic identifier and should begin with a letter or an underscore.
The parameters are declared similarly to how you declare variables specifying passing mechanism, name, datatype and if the parameter is optional.
The passing mechanism determines the interaction between the element's data type and the passing mechanism.
If you include ByVal keyword in the declaration, the subroutine makes own local copy of the parameter and then can modify this value without affecting the value of the original parameter.
If you include ByRef keyword in the declaration, the subroutine does not create a separate copy of the parameter variable.
Instead, it uses a reference to the original parameter passed into the subroutine and any changes the subroutine makes to the value are reflected in the calling subroutine too.
To declare an optional parameter you use Optional keyword, so the code that uses it may omit that parameter.
Private Sub DoSomething(Optional ByVal message As String = "") ' do something End Sub
Most importantly the subroutines allow you to extract code that you may need to use under more than one circumstance and place it in one location where you can call it as needed:
Private Sub ShowWarningMessage(ByVal message As String, ByVal title As String) MessageBox.Show( message, title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End SubThen whenever you want to warn your user you simply call the ShowWarningMessage subroutine e.g.
ShowWarningMessage("Please provide a valid email.", "Warning")Previous Lesson | Next Lesson