Section 7.18. Optional Parameters


7.18. Optional Parameters

Methods can have optional parameters. Declaring a parameter as optional allows the calling method to vary the number of arguments to pass. Optional parameters specify a default value that is assigned to the parameter if the optional argument is not passed. Overloaded methods are generally more flexible than methods with optional parameters. For instance, you can specify different return types for overloaded methods.

You can create methods with one or more optional parameters. All optional parameters, however, must be placed to the right of the method's non-optional parameters.

Common Programming Error 7.10

Declaring a non-Optional parameter to the right of an Optional parameter is a syntax error.


When a parameter is declared as optional, the caller has the option of passing that particular argument. Optional parameters are specified in the method header with keyword Optional. For example, the method header

 Sub ExampleMethod(ByVal value1 As Boolean, Optional _    ByVal value2 As Integer = 0) 


specifies the last parameter as Optional. Any call to ExampleMethod must pass at least one argument (the Boolean), or else a syntax error is generated. If the caller chooses, a second argument (the Integer) can be passed to ExampleMethod. Consider the following calls to ExampleMethod:

 ExampleMethod() ExampleMethod(True) ExampleMethod(False, 10) 


The first call to ExampleMethod generates a syntax error because a minimum of one argument is required for this method. The second call to ExampleMethod is valid because one argument (the Boolean) is being passedthe Optional argument, corresponding to parameter value2, is not specified in the method call. The last call to ExampleMethod also is valid: False is passed as the one required argument, and 10 is passed as the Optional argument.

In the call that passes only one argument (TRue) to ExampleMethod, parameter value2 defaults to 0, which is the value specified in the method header. Optional parameters must specify a default value, using the equals sign followed by the value. For example, the header for ExampleMethod sets 0 as the default value for value2. Default values can be used only with parameters declared as Optional.

Common Programming Error 7.11

Not specifying a default value for an Optional parameter is a syntax error.


The example in Fig. 7.19 demonstrates the use of optional parameters. The program calculates the result of raising a base to an exponent, both of which are specified by the user. Method Power (lines 2333) specifies that its second parameter is Optional. If the user does not specify an exponent, the Optional argument is omitted, and the default parameter value, 2, is used.

Figure 7.19. Optional argument demonstration with method Power.

  1  ' Fig. 7.19: Power.vb  2  ' Calculates the power of a value, demonstrates optional parameters.  3  Public Class FrmPower  4     ' reads input and displays result  5     Private Sub btnCalculate_Click(ByVal sender As System.Object, _  6        ByVal e As System.EventArgs) Handles btnCalculate.Click  7  8        Dim value As Integer  9 10       ' call version of Power depending on power input 11       If Not txtPower.Text = "" Then 12          value = Power(Convert.ToInt32(txtBase.Text), _ 13            Convert.ToInt32(txtPower.Text)) 14       Else 15         value = Power(Convert.ToInt32(txtBase.Text)) 16         txtPower.Text = Convert.ToString(2) 17       End If 18 19       lblOutput.Text = Convert.ToString(value) 20    End Sub  ' btnCalculate_Click 21 22    ' use iteration to calculate power 23    Function Power(ByVal base As Integer, _ 24       Optional ByVal exponent As Integer = 2) As Integer 25 26       Dim total As Integer = 1 ' initialize total 27 28       For i As Integer = 1 To exponent ' calculate power 29          total *= base 30       Next 31 32       Return total ' return result 33    End Function ' Power 34  End Class ' FrmPower 

(a)

(b)

(c)

In this example, we use TextBoxes to input data from the user. When the Calculate Power Button is clicked, line 11 determines whether txtPower contains a value. If true (as in Fig. 7.19(a)), the values in the TextBoxes are converted to Integers and passed to Power. Otherwise, txtBase's value is converted to an Integer and passed as the first of two arguments to Power in line 15. An example of this is shown in Fig. 7.19(b), where we clicked the Calculate Power Button without entering an exponent value. The second argument, 2, is provided by the compiler (using the default value of the Optional argument) and is not visible to you in the call. Line 16 displays the value 2 in txtPower, for clarity (Fig. 7.19(c)).



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net