3.2.2, 3.2.10 - Subroutines, parameters and return values (VB.NET)
Define reusable VB.NET routines, pass data into them and return results to the caller. Native answers are written without Run; the optional Python demonstration explores the same data flow.
Defining and calling subroutines
A subroutine is a named block of code that runs when another part of the program calls it.
Subroutine
A named, out-of-line block of instructions invoked by its name. A procedure performs actions; a function returns a value to its caller.
VB.NET uses Sub for a procedure and Function for a value-returning routine. Define these routines inside the module, outside each other. A definition describes the routine; it does not execute its body merely because it exists.
Module Program
Sub ShowWelcome()
Console.WriteLine("Welcome to the quiz")
End Sub
Sub Main()
ShowWelcome()
Console.WriteLine("Round 1")
End Sub
End Module
Execution starts in Main, reaches the call ShowWelcome(), executes the procedure's body, then returns to the statement after the call. The outputs are Welcome to the quiz, then Round 1. Repeating the call executes the same routine again.
Subroutines avoid copying a common task into several places. A correction to the shared routine then updates all its callers. They also separate jobs, such as obtaining data, calculating a charge and displaying a receipt, so each job can be understood and tested more easily. A meaningful name describes what the routine does; splitting every trivial statement into a routine need not improve clarity.
Passing more than one parameter
Parameters provide the data a subroutine needs for a particular call.
Sub ShowResult(ByVal playerName As String, ByVal score As Integer)
Console.WriteLine(playerName & ": " & score)
End Sub
Inside Main, ShowResult("Mina", 7) passes the text Mina into playerName and the integer 7 into score. ShowResult("Omar", 9) reuses the same body with different data. Values are matched to parameters by position in these calls. Swapping them would give unsuitable types and roles.
ByVal means the routine receives each value by value. These simple string/numeric examples do not update the caller's variables by assigning to a parameter. A function can instead return a desired result. The parameter types and order are part of the routine's interface: callers need to know what to supply.
AQA uses the word parameter for both values supplied at the call and the named receiving parameters. Other sources may call the supplied values arguments. The data flow matters: caller → named receiving values → routine's processing. A call does not automatically obtain fresh keyboard input; that happens only if the body explicitly reads it.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account