Visual Basic 2008 9.0 .NET Examples and Ebook

Procedures and Functions

Vorig Onderwerp

Arrays

|

Object Oriented Programming

Volgend Onderwerp

Methods and Arguments

Vorig Onderwerp

Introduction to Functions

|

Introduction to Object Oriented Programming

Volgend Onderwerp
Method Overloading

Method Overloading

Exercise Method Overloading

Exercise Method Overloading

Optional Parameters

Optional Parameters

Array as Parameter

Array as Parameter

Object Datatype

Object Datatype

Comparing References - Is and IsNot Operators

Comparing References - Is and IsNot Operators

Array as Parameter

Array as Parameter

Returning Arrays

Returning Arrays

Parameter Arrays

Parameter Arrays

Exercises

Exercises



Method Overloading


Different methods defined in the same module or type definition can have the same identifier. This is called "method overloading".

Next example has two ShowDouble procedures, one with an Integer parameter, and one with a String parameter.

The compiler will decide which procedure is called based upon the arguments provided by the calling routine.

When an Integer value is provided the compiler will assume that the first ShowDouble is called (1). When a String value is provided the compiler assumes that the second ShowDouble is called (2).


Module Example1
    Sub Main()
        Dim value1 As Integer = 5
        ShowDouble(value1)                                                 ' (1)
        '
        Dim value2 As String = "test"
        ShowDouble(value2)                                                 ' (2)
        '
        Console.ReadLine()
    End Sub
    Sub ShowDouble(ByVal value As Integer)                                 ' (1)
        Console.WriteLine(value * 2)
    End Sub
    Sub ShowDouble(ByVal word As String)                                   ' (2)
        Console.WriteLine(word & word)
    End Sub
End Module
Download Broncode

Output :

 10
 testtest

Next examples illustrates how different methods with the same identifier can use a different number of parameters.

Again the compiler will decide what procedure is called based upon the provided parametervalues.


Module Example2
    Sub Main()
        Console.WriteLine(GetSum(1, 2))
        Console.WriteLine(GetSum(1, 2, 3))
        Console.WriteLine(GetSum(1, 2, 3, 4))
        '
        Console.ReadLine()
    End Sub
    Function GetSum(ByVal value1 As Integer, _
                    ByVal value2 As Integer) As Integer
        GetSum = value1 + value2
    End Function
    Function GetSum(ByVal value1 As Integer, _
                    ByVal value2 As Integer, _
                    ByVal value3 As Integer) As Integer
        GetSum = value1 + value2 + value3
    End Function
    Function GetSum(ByVal value1 As Integer, _
                    ByVal value2 As Integer, _
                    ByVal value3 As Integer, _
                    ByVal value4 As Integer) As Integer
        GetSum = value1 + value2 + value3 + value4
    End Function
End Module
Download Broncode

Output :

 3
 6
 10

The "overload resoltion" of Visual Basic states that different methods with the same identifier within the same module or type definition must define parameters of different datatypes or must define a different number of parameters or must define an other order of parameter-datatypes.


Klik hier om terug naar boven te gaan.  Up



Exercise Method Overloading


Task :

Create the necessary GetCombination methods.


Module Exercise1Task
    Sub Main()
        'Console.WriteLine(GetCombination("abc", "def"))
        'Console.WriteLine(GetCombination(1, 2))
        'Console.WriteLine(GetCombination(True, True))
        'Console.WriteLine(GetCombination(True, False))
        'Console.WriteLine(GetCombination(False, True))
        'Console.WriteLine(GetCombination(False, False))
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 abcdef
 3
 True
 False
 False
 False

Solution :


Module Exercise1Solution
    Sub Main()
        Console.WriteLine(GetCombination("abc", "def"))
        Console.WriteLine(GetCombination(1, 2))
        Console.WriteLine(GetCombination(True, True))
        Console.WriteLine(GetCombination(True, False))
        Console.WriteLine(GetCombination(False, True))
        Console.WriteLine(GetCombination(False, False))
        '
        Console.ReadLine()
    End Sub
    Function GetCombination(ByVal value1 As String, _
                            ByVal value2 As String) As String
        GetCombination = value1 & value2
    End Function
    Function GetCombination(ByVal value1 As Integer, _
                            ByVal value2 As Integer) As Integer
        GetCombination = value1 + value2
    End Function
    Function GetCombination(ByVal value1 As Boolean, _
                            ByVal value2 As Boolean) As Boolean
        GetCombination = value1 AndAlso value2
    End Function
End Module
Download Broncode

Klik hier om terug naar boven te gaan.  Up



Optional Parameters


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 Example3
    Sub Main()
        Console.WriteLine(GetPower(3, 3))
        Console.WriteLine(GetPower(3))                                     ' (1)
        '
        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

Output :

 27
 9

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 Example4
    Sub Main()
        ShowSum(1)       ' value1 = 1 | value2 = 2 | value3 = 3            ' (1)
        ShowSum(2, 3)    ' value1 = 2 | value2 = 3 | value3 = 3            ' (1)
        ShowSum(4, , 5)  ' value1 = 4 | value2 = 2 | value3 = 5            ' (1)
        ShowSum(6, 7, 8) ' value1 = 6 | value2 = 7 | value3 = 8            ' (1)
        '
        ShowSum(value1:=1)                                                 ' (2)
        ShowSum(value1:=2, value2:=3)                                      ' (2)
        ShowSum(value1:=4, value3:=5)                                      ' (2)
        ShowSum(value1:=6, value2:=7, value3:=8)                           ' (2)
        '
        ShowSum(value3:=5, value1:=4)                                      ' (3)
        ShowSum(value3:=8, value2:=7, value1:=6)                           ' (3)
        '
        ShowSum(4, value3:=5)                                              ' (4)
        '
        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).


Klik hier om terug naar boven te gaan.  Up


Array as Parameter


Arrays can be passed to methods.

Important here is to remember that an arrayvariable does not contain the array itself, but contains a reference to the array-instance.

In next example parameter values will receive a copy ( ByVal ) of the reference of the array-instances ( or Nothing (1) ) contained in the arrayvariables numbers, words and dates.
So values actually points to the same array-instance as numbers, words and dates do.


Module Example5
    Sub Main()
        Dim numbers As Integer() = {1, 2, 3, 4, 5}
        PrintArray(numbers)
        '
        Dim words As String() = {"Hello", "World"}
        PrintArray(words)
        '
        Dim dates As Date()
        PrintArray(dates)                                                  ' (1)
        '
        PrintArray(Nothing)
        '
        Console.ReadLine()
    End Sub
    Sub PrintArray(ByVal values As Array)
        If values IsNot Nothing Then
            For Each element As Object In values
                Console.Write(element & " ")
            Next
            Console.WriteLine()
        Else
            Console.WriteLine("No array.")
        End If
    End Sub
End Module
Download Broncode

Output :

 1 2 3 4 5
 Hello World
 No array.
 No array.

Because numbers, words and dates are all of a different arraytype ( Integer(), String() and Date() ) parameter values must be of a type that can hold a reference to all these arraytypes.
The most suitable datatype for values is therefore Array.


Klik hier om terug naar boven te gaan.  Up


Object Datatype


The elements of the received array-instance can be of any type, in the above example of types Integer and String. Therefore the elementvariable element had to be of type Object, which can hold any type of value.

This is also illustrated in the next example.


Module Example6
    Sub Main()
        Dim object1 As Object
        '
        object1 = 5
        Console.WriteLine(object1)
        Console.WriteLine(object1 + 10)
        '
        object1 = "Hello"
        Console.WriteLine(object1)
        Console.WriteLine(object1 & " World !")
        '
        object1 = True
        Console.WriteLine(object1)
        Console.WriteLine(object1 AndAlso False)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 5
 15
 Hello
 Hello World !
 True
 False

Avoid using the Object datatype whenever possible. Working with the Object type can introduce boxing- or unboxingoperation and calls on late bound objects, which can lead to a performance overhead or even runtime type-errors.

Read the topic about value versus reference types and early versus late bound objects for more details.


Klik hier om terug naar boven te gaan.  Up


Comparing References - Is and IsNot Operators


Two references ( for instance the references holded by two arrayvariables ) can be checked for equality with the Is and IsNot operators. This in contrary to checking for equality between more primitive types where the = and <> operators are used.


Module Example7
    Sub Main()
        Dim values1 As Integer() = {1, 2, 3}
        Dim values2 As Integer() = {4, 5, 6}
        Dim values3 As Integer() = values1
        Dim values4 As Array = values2
        '
        Console.WriteLine(values1 IsNot values2)
        Console.WriteLine(values1 Is values3)
        Console.WriteLine(values1 IsNot values4)
        Console.WriteLine()
        '
        Console.WriteLine(values2 IsNot values1)
        Console.WriteLine(values2 IsNot values3)
        Console.WriteLine(values2 Is values4)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 True
 True
 True

 True
 True
 True

The expression :


 numbers1 IsNot numbers2

Could be changed to :


 Not numbers1 Is numbers2

'Nothing' is a legal value to assign to a 'Array'-variable and a 'For Each'-iteration needs a reference to a collection, that's why a check like 'values IsNot Nothing' in 'Example5' was usefull.


Klik hier om terug naar boven te gaan.  Up


Array as Parameter


Parameters can work by reference ( ByRef ) with the provided arrayreferences.


Module Example8
    Sub Main()
        Dim values As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        Example5.PrintArray(values)
        '
        DoubleIntegerValues(values, 5)
        Example5.PrintArray(values)
        '
        ResizeIntegerArray(values, 20)
        Example5.PrintArray(values)
        '
        Console.ReadLine()
    End Sub
    Sub DoubleIntegerValues(ByVal values As Integer(), ByVal count As Integer)
        For index As Integer = 0 To count - 1
            values(index) *= 2
        Next
    End Sub
    Sub ResizeIntegerArray(ByRef values As Integer(), ByVal capacity As Integer)
        ReDim values(capacity - 1)
    End Sub
End Module
Download Broncode

Output :

 1 2 3 4 5 6 7 8 9 10
 2 4 6 8 10 6 7 8 9 10
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

values of DoubleIntegerValues works with a copy ( "by value" / ByVal ) of the provided arrayreference. Therefore variables values of Main and values of DoubleIntegerValues will hold the same reference and will point to the same arrayinstance.

Procedure 'ResizeIntegerArray' wants to resize the array provided to that routine. A 'ReDim' statement can be used for that purpose. 'ReDim' will create a new arrayinstance, and store the reference to that new instance in the variable being used in the statement. So the content of the arrayvariable provided when calling 'ResizeIntegerArray' needs to change, therefore we'll need to work "by reference" ( 'ByRef' ) with the provided argumentvalues.


Klik hier om terug naar boven te gaan.  Up


Returning Arrays


A function can return an array. The type specifier ( As clause ) of that function defines what arraytype is being returned.

Function GetIntegerArray of Example9 will return an Integer array.


Module Example9
    Sub Main()
        Dim values As Integer()
        Example5.PrintArray(values)
        '
        values = GetIntegerArray(10)
        Example5.PrintArray(values)
        '
        Console.ReadLine()
    End Sub
    Function GetIntegerArray(ByVal capacity As Integer) As Integer()
        Dim integerArray(capacity - 1) As Integer
        GetIntegerArray = integerArray
    End Function
End Module
Download Broncode

Output :

 No array.
 0 0 0 0 0 0 0 0 0 0

A call to the GetIntegerArray function is an expression of type Integer().


Klik hier om terug naar boven te gaan.  Up


Parameter Arrays


When a methods needs to work with an arbitrary number of argumentvalues of a specific type, a "parameterarray" ( keyword ParamArray ) with element of that type can be used.

In Example10 function GetSum must deliver the sum of an arbitrary number of Integer values.

Paramarray values will hold a reference of an Integer array containing the provided values.


Module Example10
    Sub Main()
        Console.WriteLine(GetSum(1, 2, 3, 4, 5))
        Console.WriteLine(GetSum(1, 2, 3, 4))
        Console.WriteLine(GetSum(1, 2, 3))
        Console.WriteLine(GetSum(1, 2))
        Console.WriteLine(GetSum(1))
        Console.WriteLine(GetSum())                                        ' (1)
        '
        Console.ReadLine()
    End Sub
    Function GetSum(ByVal ParamArray values As Integer()) As Integer
        If values IsNot Nothing Then
            For Each value As Integer In values
                GetSum += value
            Next
        End If
    End Function
End Module
Download Broncode

Output :

 15
 10
 6
 3
 1
 0

The implementation of GetSum can use values as any other array would be used.

It is possible to provide no values for a parameterarray (1). In that case will the ParamArray variable hold a reference to an empty ( without elements ) arrayinstance. The selection If values IsNot Nothing Then is not needed in this situation.

ByRef ParamArray is an illegal combination. One can only work "by value" ( ByVal ) with the provides values.

There can be only one parameterarray in an argumentslist, and this 'ParamArray' must be at the end of the parameterslist. If not, the compiler couldn't know which values need to be assigned to which parameters.

ParamArray can not be combined with optional parameters.


Module Example11
    Sub Main()
        Dim values As Integer() = {1, 2, 3, 4, 5}
        Console.WriteLine(Example10.GetSum(values))
        '
        values = Nothing
        Console.WriteLine(Example10.GetSum(values))                        ' (1)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 15
 0

As the above example illustrates a parameterarray can work with a provided arrayreference. For this purpose the ParamArray keyword was not necessary.

It is however syntactily correct to assign Nothing to an arrayvariable, therefore it is possible to provide Nothing to an parameterarray. In that case a condition like values IsNot Nothing can be usefull.

Example10.GetSum will only iterate over the elements of values when values is not Nothing, otherwise the For Each would trigger an exception.


Klik hier om terug naar boven te gaan.  Up


Exercises


Create a module Exercise2Solution with function GetConcatenation.


Module Exercise2Task
    Sub Main()
        Console.WriteLine(Exercise2Solution.GetConcatenation("abc", "def", _
                                                             "ghi"))
        Console.WriteLine(Exercise2Solution.GetConcatenation("abc", "def"))
        Console.WriteLine(Exercise2Solution.GetConcatenation("abc"))
        Console.WriteLine(Exercise2Solution.GetConcatenation())
        '
        Dim words As String() = {"abc", "def", "ghi"}
        Console.WriteLine(Exercise2Solution.GetConcatenation(words))
        '
        words = Nothing
        Console.WriteLine(Exercise2Solution.GetConcatenation(words))
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 abcdefghi
 abcdef
 abc

 abcdefghi

Solution :


Module Exercise2Solution
    Function GetConcatenation(ByVal ParamArray words As String()) As String
        If words IsNot Nothing Then
            For Each word As String In words
                GetConcatenation &= word
            Next
        End If
    End Function
End Module
Download Broncode

Create module Exercise3Solution with the methods GetArrayCopy and MultiplyIntegerValues.


Module Exercise3Task
    Sub Main()
        Dim values As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        Example5.PrintArray(values)
        '
        Dim count As Integer = 5
        Dim valuesCopy As Integer()
        valuesCopy = Exercise3Solution.GetIntegerArrayCopy(values, count)
        Example5.PrintArray(valuesCopy)
        '
        Dim factor As Integer = 4
        count = 3
        Exercise3Solution.MultiplyIntegerValues(valuesCopy, count, factor)
        '
        Example5.PrintArray(values)
        Example5.PrintArray(valuesCopy)
        '
        count = 6
        Exercise3Solution.MultiplyIntegerValues(values, count)
        '
        Example5.PrintArray(values)
        Example5.PrintArray(valuesCopy)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 1 2 3 4 5 6 7 8 9 10
 1 2 3 4 5
 1 2 3 4 5 6 7 8 9 10
 4 8 12 4 5
 2 4 6 8 10 12 7 8 9 10
 4 8 12 4 5

Solution :


Module Exercise3Solution
    Function GetIntegerArrayCopy(ByVal values As Integer(), _
                                 ByVal count As Integer) As Integer()
        Dim valuesCopy(count - 1) As Integer
        For index As Integer = 0 To count - 1
            valuesCopy(index) = values(index)
        Next
        GetIntegerArrayCopy = valuesCopy
    End Function
    Sub MultiplyIntegerValues(ByVal values As Integer(), _
                              ByVal count As Integer, _
                              Optional ByVal factor As Integer = 2)
        For index As Integer = 0 To count - 1
            values(index) *= factor
        Next
    End Sub
End Module
Download Broncode




This version ( published on 2008-06-24 ) is printed from http://www.studyvb.com, visit the website for more recent information.

Updated On : 2008-04-04

Download Broncode

Published On : 2008-06-24

Methods and Arguments

Vorig Onderwerp

Introduction to Functions

|

Introduction to Object Oriented Programming

Volgend Onderwerp

Procedures and Functions

Vorig Onderwerp

Arrays

|

Object Oriented Programming

Volgend Onderwerp
Nederlands  Nederlands

Add to favorites (IE).