Procedures (Functions and Subroutines)
Procedures are named blocks of code that perform a specific task. In Visual Basic .NET, procedures are implemented as either Sub
procedures (subroutines) or Function
procedures. Subroutines perform an action but do not return a value, while functions perform an action and return a value.
Sub Procedures (Subroutines)
Sub
procedures are used to perform actions. They do not return a value to the calling code. You call a Sub
procedure using its name.
Syntax
Sub ProcedureName(Optional arg1 As DataType, Optional arg2 As DataType) ' Code to execute End Sub
Example
Sub GreetUser(ByVal userName As String) Console.WriteLine("Hello, " & userName & "!") End Sub ' Calling the Sub procedure GreetUser("Alice")
Function Procedures
Function
procedures perform actions and return a single value to the calling code. The return type of the function is specified after the parameter list.
Syntax
Function FunctionName(Optional arg1 As DataType, Optional arg2 As DataType) As ReturnDataType ' Code to execute FunctionName = "Some Value" ' Assign the return value End Function
Example
Function AddNumbers(ByVal num1 As Integer, ByVal num2 As Integer) As Integer AddNumbers = num1 + num2 End Function ' Calling the Function procedure Dim result As Integer result = AddNumbers(5, 10) Console.WriteLine("The sum is: " & result) ' Output: The sum is: 15
Parameter Passing
Parameters can be passed to procedures in two ways:
- ByVal: A copy of the variable is passed. Changes made to the parameter within the procedure do not affect the original variable. This is the default.
- ByRef: A reference to the variable is passed. Changes made to the parameter within the procedure affect the original variable.
Note: It is generally recommended to use ByVal
unless you explicitly need to modify the original variable within the procedure.