Optional Parameters

Team-Fly    

 
Application Development Using Visual Basic and .NET
By Robert J. Oberg, Peter Thorsteinson, Dana L. Wyatt
Table of Contents
Chapter 4.  VB.NET Essentials, Part II


VB.NET allows parameters to be defined as optional. That is, the calling statement may or may not pass a value for that parameter. If optional parameters are defined, a default value for them must be specified. When arguments are passed, the actual argument is used. When no argument is passed, the default value for the parameter is used.

To define a parameter as optional, the keyword Optional is used. The default value for the parameter is specified using the assignment operator and a value after the declaration. The example OptionalParameters illustrates the use of these parameters.

 graphics/codeexample.gif ' Calculates shipping costs; assumes that the Rapid Express ' is the default shipper. Shipper codes are: ' 1=Rapid Express, 2=Quick Shippers, 3=SS Transport Private Function CalcCost(ByVal weight As Integer, _  Optional ByVal shipper As Integer = 1) As Decimal    Select Case shipper       Case 1          ' calculate cost for Rapid Express          Return 11.5 + (weight - 1) * 7.95       Case 2          ' calculate cost for Quick Shippers          Return 19 + (weight - 1) * 4.25       Case 3          ' calculate cost for SS Transport          Return 2.9 + (weight - 1) * 2.25    End Select    Return -1 End Function 

This function can be called in any of the following ways:

 Dim sc As Decimal sc = CalcCost(4)    ' omit optional parameter sc = CalcCost(4, 1) ' specify default for optional                     ' parameter sc = CalcCost(4, 3) ' specify any value for optional 

Optional parameters are most useful when a procedure is typically called with a certain value for a procedure, but may occasionally be called with a different value.

Optional Parameters Must Specify a Default Value

VB6 programmers should be aware that VB.NET requires all optional parameters to specify a default value. In VB6, this was not the case. A VB6 programmer could use the function IsMissing to determine whether a parameter was passed. IsMissing is not supported in VB.NET.


Team-Fly    
Top
 


Application Development Using Visual BasicR and .NET
Application Development Using Visual BasicR and .NET
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 190

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