Subroutines and functions aren’t entirely isolated from the rest of the application. Most procedures accept arguments from the calling program. Recall that an argument is a value you pass to the procedure and on which the procedure usually acts. This is how subroutines and functions communicate with the rest of the application.
Subroutines and functions may accept any number of arguments, and you must supply a value for each argument of the procedure when you call it. Some of the arguments may be optional, which means you can omit them; you will see shortly how to handle optional arguments.
The custom function Min(), for instance, accepts two numbers and returns the smaller one:
Function Min(ByVal a As Single, ByVal b As Single) As Single
Min = IIf(a < b, a, b)
End Function
Code language: VB.NET (vbnet)
IIf() is a built-in function that evaluates the first argument, which is a logical expression. If the expression is True, the IIf() function returns the second argument. If the expression is False, the function returns the third argument.
To call the Min() custom function, use a few statements like the following:
Dim val1 As Single = 33.001
Dim val2 As Single = 33.0011
Dim smallerVal as Single
smallerVal = Min(val1, val2)
Debug.Write("The smaller value is " & smallerVal)
Code language: VB.NET (vbnet)
If you execute these statements (place them in a button’s Click event handler), you will see the following in the Immediate window:
The smaller value is 33.001
Code language: VB.NET (vbnet)
If you attempt to call the same function with two Double values, with a statement like the following, you will see the value 3.33 in the Immediate window:
Debug.WriteLine(Min(3.33000000111, 3.33000000222))
Code language: VB.NET (vbnet)
The compiler converted the two values from Double to Single data type and returned one of them. Which one is it? It doesn’t make a difference because when converted to Single, both values are the same.
Interesting things will happen if you attempt to use the Min() function with the Strict option turned on. Insert the statement Option Strict On at the very beginning of the file, or set Option Strict to On in the Compile tab of the project’s Properties pages. The editor will underline the statement that implements the Min() function: the IIf() function. The IIf() function accepts two Object variables as arguments, and returns one of them as its result. The Strict option prevents the compiler from converting an Object to a numeric variable. To use the IIf() function with the Strict option, you must change its implementation as follows:
Function Min(ByVal a As Object, ByVal b As Object) As Object
Min = IIf(Val(a) < Val(b), a, b)
End Function
Code language: VB.NET (vbnet)
It’s possible to implement a Min() function that can compare arguments of all types (integers, strings, dates, and so on). We’ll return to this sample function later in this chapter, in the section “Overloading Functions.”