|
|
 |
|
|
|
|
|
|
|
|
Visual Basic 2008 9.0 .NET Examples and Ebook
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| Parameter can be defined as optional by placing the Optional keyword before ByVal or ByRef and by assigning a defaultvalue to that paramter.
The defaultvalue is used when the call provides no parametervalue for that argument.
The second call (1) in next example will use 2 for parameter exponent. |
| Module Example1
Sub Main()
Console.WriteLine(GetPower(3, 3))
Console.WriteLine(GetPower(3))
Console.ReadLine()
End Sub
Function GetPower(ByVal base As Integer, _
Optional ByVal exponent As Integer = 2) As Integer
GetPower = base ^ exponent
End Function
End Module Download Broncode |
| Defaultvalues are mandatory on Optional parameters, and can not be used on nonoptional parameters. The defaultvalue must be expressed by a constant expression ( for instance a literal ), that is know at compiletime.
Methods can define more than one Optional parameter. In that case all optional parameters must be places at the end of the parameterlist. |
| Module Example2
Sub Main()
ShowSum(1)
ShowSum(2, 3)
ShowSum(4, , 5)
ShowSum(6, 7, 8)
ShowSum(value1:=1)
ShowSum(value1:=2, value2:=3)
ShowSum(value1:=4, value3:=5)
ShowSum(value1:=6, value2:=7, value3:=8)
ShowSum(value3:=5, value1:=4)
ShowSum(value3:=8, value2:=7, value1:=6)
ShowSum(4, value3:=5)
Console.ReadLine()
End Sub
Sub ShowSum(ByVal value1 As Integer, _
Optional ByVal value2 As Integer = 2, _
Optional ByVal value3 As Integer = 3)
Console.WriteLine(value1 + value2 + value3)
End Sub
End Module Download Broncode |
| Output : 6
8
11
21
6
8
11
21
11
21
8 |
| Use commas to indicate which parametervalues should be assigned to which parametervariables.
Since Visual Basic 9.0 ( 2008 ) argument can also be passed by name (2).
The order in which the parametervalues are provided is arbitrary when all parametervalues are passed by name (3).
A combination of argument passing by position and by name is possible (4). |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|