vb.net console application program
DESCRIPTION
All type of VB.NET console application programs.More than 300 programs .TRANSCRIPT
2
'Simple Visual Basic program.
Module module1
Sub Main()
Console.WriteLine("Welcome to Visual Basic!")
End Sub ' Main
End Module
'Writing line of text with multiple statements
Module Tester1
Sub Main()
Console.Write("Welcome to ")
Console.WriteLine("Visual Basic!")
End Sub ' Main
End Module
'Every console app starts with Main
Module HelloWorld
Sub Main()
System.Console.WriteLine("Hello world!")
End Sub
End Module
'Read a single character
Module Module4
Sub Main()
Dim strChar As String
Console.Write("Enter a character: ")
strChar = Console.ReadKey.KeyChar
'strChar = Console.ReadKey(True).KeyChar
Console.WriteLine()
Console.WriteLine("You just entered {0}.", strChar)
End Sub
End Module
'Read a complete line of text
Module Module5
3
Sub Main()
Dim strLine As String
Console.Write("Enter a line of text: ")
strLine = Console.ReadLine
Console.WriteLine()
Console.WriteLine("You just entered: {0}", strLine)
End Sub
End Module
'Read a string from console
Module Module6
Sub Main()
Dim strMessage As String
Try
strMessage = Console.ReadLine()
Console.WriteLine("HELLO " + strMessage)
Catch ex As Exception
End Try
End Sub
End Module
'Use Do Loop to read user input
Module Module9
Sub Main()
Dim strInput As String
Do
Console.WriteLine("Please enter 'q' to quit...")
strInput = Console.ReadLine()
Console.WriteLine("You typed " & strInput)
Loop While (strInput <> "q")
Console.WriteLine("Quitting now.")
End Sub
End Module
'Use While to read user input
Module Module12
Sub Main()
Console.WriteLine("Please enter 'q' to quit...")
Dim strInput As String = Console.ReadLine()
4
While (strInput <> "q")
Console.WriteLine("You typed " & strInput)
Console.WriteLine("Please enter 'q' to quit...")
strInput = Console.ReadLine()
End While
Console.WriteLine("Quitting now.")
End Sub
End Module
'Output string to the Console
Module Module14
Sub Main()
Console.WriteLine("Hello from Module")
End Sub
End Module
'Variable index
Public Class Tester15
Public Shared Sub Main()
Console.WriteLine(String.Format("There are about {0}
days in {1} years.", 365.25 * 3, 3, 17))
End Sub
End Class
'Write some text based on the specified data type
Module Module16
Sub Main()
Console.Write(True)
Console.Write(25)
Console.Write("Some text.")
Console.WriteLine()
Console.WriteLine()
Console.WriteLine(True)
Console.WriteLine(25)
Console.WriteLine("Some text.")
End Sub
End Module
5
'Concatenate strings in Console.WriteLine statement
Module Module17
Sub Main()
Dim WebSite As String
Dim Publisher As String = "AAAA"
Console.WriteLine("AAAA: " & Publisher)
WebSite = "CCCC." & Publisher & ".DDDD"
Console.WriteLine("String one " & WebSite)
End Sub
End Module
'Reference variable index in Console.WriteLine
Module Module18
Sub Main()
Dim A As Double = 1.23456789
Console.WriteLine("{0} {1} {2}", 10, 2, 3)
End Sub
End Module
'Use Console.WriteLine to display various type variables
Module Module19
Sub Main()
Dim A As Integer = 100
Dim B As Double = 0.123456789
Dim Message As String = "Hello, VB World!"
Console.WriteLine(A)
Console.WriteLine("The value of A is " & A)
Console.WriteLine(B)
Console.WriteLine(B & " plus " & A & " = " & B + A)
Console.WriteLine(Message)
End Sub
End Module
6
'Demonstrates scope rules and instance variables
Public Class Tester20
' instance variable can be used anywhere in class
Shared value As Integer = 1
' demonstrates class scope and block scope
Public Shared Sub Main()
Dim value As Integer = 5
Console.WriteLine("local variable value in" & "
FrmScoping_Load is " & value)
MethodA() ' MethodA has automatic local value
MethodB() ' MethodB uses instance variable value
MethodA() ' MethodA creates new automatic local value
MethodB() ' instance variable value retains its value
Console.WriteLine("local variable " & "value in
FrmScoping_Load is " & value)
End Sub
' automatic local variable value hides instance variable
Shared Sub MethodA()
Dim value As Integer = 25 ' initialized after each
call
Console.WriteLine("local variable " & "value in
MethodA is " & value & " after entering MethodA")
value += 1
Console.WriteLine("local variable " & "value in
MethodA is " & value & " before exiting MethodA")
End Sub
' uses instance variable value
Shared Sub MethodB()
Console.WriteLine("instance variable" & " value is " &
value & " after entering MethodB")
value *= 10
Console.WriteLine("instance variable " & "value is " &
value & " before exiting MethodB")
End Sub
End Class
7
'Block scope
Option Strict On
Public Class BlockScope
Public Shared Sub Main()
For outerLoop As Integer = 0 To 10000
For innerLoop As Integer = 0 To 10
Dim blockVar As Integer
blockVar += 1
If blockVar Mod 1000 = 0 Then
Console.WriteLine(blockVar)
End If
Next
Next
End Sub
End Class
'Variable block scope
Public Class Test22
Public Shared Sub Main()
For i As Integer = 1 To 5
Dim j As Integer = 3
If i = j Then
Dim M As Integer = i + j
Console.WriteLine("M: " & M)
Else
Dim N As Integer = i * j
Console.WriteLine("N: " & N)
End If
Dim k As Integer = 123
Console.WriteLine("k: " & k)
Next i
End Sub
End Class
'Variable scope in try catch statement
Public Class Test23
Public Shared Sub Main()
Try
Dim i As Integer = CInt("bad value")
Catch ex As InvalidCastException
Dim txt As String = "InvalidCastException"
Console.WriteLine(txt)
Catch ex As Exception
Dim txt As String = "Exception"
Console.WriteLine(txt)
End Try
End Sub
End Class
8
'Define variable inside If statement
Public Class Test24
Public Shared Sub Main()
Dim manager As Boolean = True
If manager Then Dim txt As String = "M" :
Console.WriteLine(txt) Else _
Dim txt As String = "E" : Console.WriteLine(txt)
End Sub
End Class
'Sub scope()
Public Class Test25
Public Shared Sub Main()
DisplayHowardsName()
DisplayStephsName()
End Sub
Shared Sub DisplayStephsName()
Dim myName As String
myName = "A"
Console.WriteLine(myName)
End Sub
Shared Sub DisplayHowardsName()
Dim myName As String
myName = "B"
Console.WriteLine(myName)
End Sub
End Class
'Function local variables
Module Module26
Sub F()
Dim Name As String = "www.java2s.com"
Dim Price As Double = 17.45
Dim I As Integer = 1001
Console.WriteLine("In F")
Console.WriteLine("Name: " & Name)
Console.WriteLine("Price: " & Price)
Console.WriteLine("I: " & I)
End Sub
9
Sub FF()
Dim Name As String = "string"
Dim Price As Double = 49.99
Dim I As Integer = 0
Console.WriteLine("In FF")
Console.WriteLine("Name: " & Name)
Console.WriteLine("Price: " & Price)
Console.WriteLine("I: " & I)
End Sub
Sub Main()
F()
Console.WriteLine()
FF()
End Sub
End Module
'Local variable shadows global variable with the same name
Module Module27
Dim Counter As Integer
Sub BigLoop()
For Counter = 1000 To 1005 ' Use global Counter
Console.Write(Counter & " ")
Next
End Sub
Sub LittleLoop()
Dim Counter As Integer
For Counter = 0 To 5 ' Use local Counter
Console.Write(Counter & " ")
Next
End Sub
Sub Main()
Counter = 100
Console.WriteLine("Starting Counter: " & Counter)
BigLoop()
Console.WriteLine("Counter after BigLoop: " & Counter)
LittleLoop()
Console.WriteLine("Counter after LittleLoop: " &
Counter)
If (Counter > 1000) Then
Dim Counter As Integer = 0
10
Console.WriteLine("Counter in If statement: " & Counter)
End If
Console.WriteLine("Ending Counter: " & Counter)
End Sub
End Module
'Module global variable
Module Module29
Sub Main()
For intLoopIndex As Integer = 0 To 5
System.Console.WriteLine(Tracker())
Next intLoopIndex
End Sub
Dim intCount As Integer
Function Tracker() As Integer
intCount += 1
Return intCount
End Function
End Module
'class definition with namespace
Namespace WinForms
Public Class HelloWorld
Shared Sub Main()
System.Console.WriteLine("Hello World")
End Sub
End Class
End Namespace
'Define your own namespace
Namespace MyNamespace
Public Class Class2
End Class
End Namespace
Namespace MyNamespace
Public Class Class1
End Class
11
End Namespace
Module mod1
Sub main()
Dim objClass2 As MyNamespace.Class2
Dim objClass1 As MyNamespace.Class1
End Sub
End Module
'MUse Namespace
Namespace MyApp.Info
Module Main
Sub Main()
Dim objHW As New MyApp.Info.Utilities
objHW.DisplayData()
End Sub
End Module
Public Class Utilities
'Run the application
Public Sub DisplayData()
Console.WriteLine(Environment.MachineName)
Console.WriteLine(Environment.SystemDirectory)
Console.WriteLine(Environment.GetLogicalDrives())
Console.WriteLine(Environment.Version.ToString())
End Sub
End Class
End Namespace
'Use namespace to remove the conflicts
Namespace Network
Class Address
Public IP As String
Public DomainName As String
Public Sub New(ByVal IPAddr As String, ByVal Domain As
String)
IP = IPAddr
DomainName = Domain
End Sub
Public Sub ShowAddress()
Console.WriteLine("IP: " & IP)
Console.WriteLine("Domain: " & DomainName)
End Sub
End Class
End Namespace
12
Namespace Mailing
Class Address
Public Street As String
Public City As String
Public State As String
Public Zip As String
Public Sub New(ByVal Street As String, ByVal City As
String, ByVal State As String, ByVal Zip As String)
Me.Street = Street
Me.City = City
Me.State = State
Me.Zip = Zip
End Sub
Public Sub ShowAddress()
Console.WriteLine("Street: " & Street)
Console.WriteLine("City: " & City)
Console.WriteLine("State: " & State)
Console.WriteLine("Zip: " & Zip)
End Sub
End Class
End Namespace
Module Module32
Sub Main()
Dim IP As New Network.Address("122.111.222.112",
"www.SomeSite.com")
Dim address As New Mailing.Address("122 Main",
"Houston", "Texas", "77469")
IP.ShowAddress()
Console.WriteLine()
address.ShowAddress()
End Sub
End Module
'Static Variable
Option Strict On
Public Module Test33
Public Sub Main()
For loopCtr As Integer = 1 To 10
Console.WriteLine(Invocations())
Next
End Sub
13
Private Function Invocations() As Integer
Static i As Integer
i += 1
Return i
End Function
End Module
'Call static method
Option Strict On
Public Module CallStaticMethod
Public Sub Main()
Console.WriteLine(Greeting.SayHello())
End Sub
End Module
Public Class Greeting
Public Shared Function SayHello() As String
Return "And a top of the morning to you!"
End Function
End Class
'Cause compiler error when Option Strict On
Module Module36
Sub Main()
Dim AnInt As Integer = 5
Dim ALong As Long = 7
ALong = AnInt
'causes compiler error when Option Strict On
'AnInt = ALong
MsgBox(AnInt)
End Sub
End Module
'Option Explicit Off
Option Explicit Off
Module Explicit
Public Sub Main()
For ctr As Integer = 0 To 100
' Do something
result = cntr
Next
Console.WriteLine("The counter reached " & result &
".")
End Sub
End Module
14
'Turn Explicit off to use variable without declaration
Option Explicit Off
Module Module37
Sub Main()
EmployeeName = "Buddy Jamsa"
EmployeePhoneNumber = "555-1212"
EmployeeSalary = 45000.0
NumberOfEmployees = 1
Console.WriteLine("Number of employees: " &
NumberOfEmployees)
Console.WriteLine("Employee name: " & EmployeeName)
Console.WriteLine("Employee phone number: " &
EmployeePhoneNumber)
Console.WriteLine("Employee salary: " &
EmployeeSalary)
End Sub
End Module
'Hexadecimal Byte, UInteger and Integer
Option Strict On
Public Module modul38
Public Sub Main()
Dim maxValue As Byte = &HFF
Dim posValue As UInteger = &HF034
Dim negValue As Integer = &HF034
Console.WriteLine(maxValue)
Console.WriteLine(posValue)
Console.WriteLine(negValue)
End Sub
End Module
Public Class m39
Public Shared Sub Main()
Dim result As New System.Text.StringBuilder()
Dim maxByte As Byte = Byte.MaxValue
Dim maxSByte As SByte = SByte.MaxValue
Dim maxShort As Short = Short.MaxValue
Dim maxUShort As UShort = UShort.MaxValue
Dim maxInteger As Integer = Integer.MaxValue
Dim maxUInteger As UInteger = UInteger.MaxValue
15
Dim maxLong As Long = Long.MaxValue
Dim maxULong As ULong = ULong.MaxValue
Console.WriteLine("" & maxByte)
Console.WriteLine("" & maxSByte)
Console.WriteLine("" & maxShort)
Console.WriteLine("" & maxUShort)
Console.WriteLine("" & maxInteger)
Console.WriteLine("" & maxUInteger)
Console.WriteLine("" & maxLong)
Console.WriteLine("" & maxULong)
End Sub
End Class
'Swap two integers without using a third
Public Class m40
Public Shared Sub Main()
Dim firstValue As Integer
Dim secondValue As Integer
firstValue = 17
secondValue = 123
Console.WriteLine("Before swap: {0}, {1}", firstValue,
secondValue)
firstValue = firstValue Xor secondValue
secondValue = firstValue Xor secondValue
firstValue = firstValue Xor secondValue
Console.WriteLine("After swap: {0}, {1}", firstValue,
secondValue)
End Sub
End Class
'Parse Integer
Public Class m41
Public Shared Sub Main()
Try
Dim num_items As Integer = Integer.Parse("123")
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Class
16
'Integer boolean calculation: Or, And, Xor, Not
Public Class m42
Public Shared Sub Main()
Dim I As Integer
I = 3 Or 4
Console.WriteLine(I)
I = 2 And 4
Console.WriteLine(I)
I = 3 Xor 3
Console.WriteLine(I)
I = Not 5
Console.WriteLine(I)
End Sub
End Class
'Use Integer.CompareTo to compare two integers
Public Class m43
Public Shared Sub Main()
Dim I As Integer = 0
Dim S As Integer = 8
Console.WriteLine(I.CompareTo(S))
End Sub
End Class
'Integer format: D10
Public Class m44
Public Shared Sub Main()
Dim intNumber As Integer = 12345
Console.WriteLine(intNumber.ToString("D10"))
End Sub
End Class
'Pass Integer to a function by reference
Module M45
Sub ParameterChange(ByRef A As Integer)
A = 1001
Console.WriteLine("Value of A in subroutine " & A)
End Sub
Sub Main()
Dim Number As Integer = 100
Console.WriteLine("Number before function call: " &
17
Number)
ParameterChange(Number)
Console.WriteLine("Number before function call: " &
Number)
End Sub
End Module
'Pass Integer to a function by value
Module M46
Sub NoChangeToParameter(ByVal A As Integer)
A = 1001
Console.WriteLine("Value of A in subroutine " & A)
End Sub
Sub Main()
Dim Number As Integer = 100
Console.WriteLine("Number before function call: " &
Number)
NoChangeToParameter(Number)
Console.WriteLine("Number before function call: " &
Number)
End Sub
End Module
'Compare Integer value in If statement
Module M47
Sub Main()
Dim TestScore As Integer = 80
If TestScore >= 90 Then
Console.WriteLine("Test grade: A")
ElseIf TestScore >= 80 Then
Console.WriteLine("Test grade: B")
ElseIf TestScore >= 70 Then
Console.WriteLine("Test grade: C")
Else
Console.WriteLine("Test grade: F")
End If
End Sub
End Module
18
'Integer OverflowException
Public Class m48
Public Shared Sub Main()
Dim A, B As Integer
Dim C As Integer
Try
A = 9999
B = 9999
C = A * B * B * B
Catch Except As OverflowException
Console.WriteLine("Overflow error detected")
End Try
End Sub
End Class
'Implicit conversion of an integer to a string
Module m49
Public Sub Main()
Dim iInteger As Integer = 5280
'Dim lLong As Long
'Dim bytByte As Byte
'Dim sngSingle As Single
'Dim dblDouble As Double
'Dim decDecimal As Decimal
Console.WriteLine("Implicit conversion of an integer
to a string: {0}", iInteger)
End Sub
End Module
'Explicit conversion of an integer to a string
Module m50
Public Sub Main()
Dim iInteger As Integer = 5280
'Dim lLong As Long
'Dim bytByte As Byte
'Dim sngSingle As Single
'Dim dblDouble As Double
'Dim decDecimal As Decimal
Console.WriteLine("Explicit conversion of an integer
to a string: {0}", CStr(iInteger))
End Sub
End Module
19
'Double.IsNaN()
Module M51
Sub Main()
If (Double.IsNaN("1.2")) Then
Console.WriteLine("Not a Number.")
End If
End Sub
End Module
'Double.IsNegativeInfinity()
Module MyModule52
Sub Main()
If (Double.IsNegativeInfinity("0.0000000000000001"))
Then
Console.WriteLine("Negative infinity.")
End If
End Sub
End Module
'Char.ToUpper
Public Class m53
Public Shared Sub Main()
Console.WriteLine(Char.ToUpper("a"))
End Sub
End Class
'vbNewLine
Public Class m54
Public Shared Sub Main()
Console.WriteLine("a" & vbNewLine & "b")
End Sub
End Class
'Concatenate vbTab with Integer
Option Strict On
Module M55
Sub Main()
Dim counter As Integer
20
For counter = 1 To 100
Console.Write("{0} ", counter)
If counter Mod 10 = 0 Then
Console.WriteLine(vbTab & counter)
End If
Next counter
End Sub
End Module
'Define Boolean value and use it in If statement
Public Class m56
Public Shared Sub Main()
Dim blnStatus As Boolean = True
Console.WriteLine(blnStatus)
blnStatus = Not blnStatus
Console.WriteLine(blnStatus)
If blnStatus Then
Console.WriteLine("The status is true.")
Else
Console.WriteLine("The status is false.")
End If
End Sub
End Class
'Define Enum and assign value
Module M57
Enum Temperatures
A = 0
B = 32
C = 60
D = 72
E = 212
End Enum
Sub Main()
System.Console.WriteLine("B: {0}", Temperatures.B)
System.Console.WriteLine("E: {0}", Temperatures.E)
End Sub
End Module
21
'Demonstrating overflows with and without checking
Class m58
Shared Sub Main()
Try
Dim number1 As Integer = Int32.MaxValue '
2,147,483,647
Dim number2 As Integer = Int32.MaxValue '
2,147,483,647
Dim sum As Integer = 0
Console.WriteLine("number1: {0}" & vbCrLf & _
"number2: {1}", number1, number2)
Console.WriteLine("Sum integers in checked
context:")
sum = number1 + number2 ' compute sum
Console.WriteLine("Sum after operation: {0}", sum)
Catch overflowExceptionParameter As OverflowException
Console.WriteLine(overflowExceptionParameter.ToString())
End Try
End Sub
End Class
'Join string
Public Class m59
Public Shared Sub Main()
Dim s() As String = {"one", "two", "three"}
'a string array
Dim s2 As String
s2 = String.Join(": ", s)
Console.WriteLine(s2)
End Sub
End Class
'Copy characters from string1 into character Array
Module m60
Sub Main()
Dim string1 As String
22
Dim characterArray As Char()
Dim i As Integer
Dim quotes As Char = ChrW(34)
string1 = "hello there"
characterArray = New Char(5) {}
string1.CopyTo(0, characterArray, 0, 5)
For i = 0 To characterArray.GetUpperBound(0)
Console.WriteLine(characterArray(i))
Next
End Sub ' Main
End Module
'String Length property
Module m61
Sub Main()
Dim string1 As String
'Dim characterArray As Char()
'Dim i As Integer
Dim quotes As Char = ChrW(34)
string1 = "hellothere"
'characterArray = New Char(5) {}
Console.WriteLine("Length of string1: " &
string1.Length)
End Sub ' Main
End Module
'Catch Exception for String.Substring
Public Class m62
Public Shared Sub Main()
Dim strCaption As String
strCaption = "Answer"
Try
Console.WriteLine(strCaption.Substring(10, 1))
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Class
23
'Make a reference copy
Public Class m63
Public Shared Sub Main()
Dim arrayA() As String = {"One", "Two", "Three",
"Four", "Five", "Six"}
Console.WriteLine(Join(arrayA, ","))
Dim arrayB() As String = {"A", "B", "C", "D", "E",
"E", "F", "G", "H"}
Console.WriteLine(Join(arrayB, ","))
' ----- Make a reference copy.
Dim arrayC() As String = arrayA
Console.WriteLine(Join(arrayC, ","))
End Sub
End Class
'String Concatenate
Class m64
Public Shared Sub Main()
Dim s1 As String = "abcd"
Dim s2 As String = "ABCD"
' concatenation method
Dim s3 As String = String.Concat(s1, s2)
Console.WriteLine("s3 concatenated from s1 and s2:
{0}", s3)
End Sub 'Main
End Class 'Tester
'Use the overloaded operator
Class m65
Public Shared Sub Main()
Dim s1 As String = "abcd"
Dim s2 As String = "ABCD"
Dim s4 As String = s1 & s2
Console.WriteLine("s4 concatenated from s1 & s2:" +
s4)
End Sub 'Main
End Class 'Tester
24
'Array.Reverse a string array
Public Class m66
Public Shared Sub Main()
Dim StringArray() As String = {"This", "is", "a",
"test"}
Array.Reverse(StringArray)
Dim E As IEnumerator = StringArray.GetEnumerator()
While (E.MoveNext())
Console.WriteLine(E.Current())
End While
End Sub
End Class
'Comparing strings: Equals, =, String.Equals() and CompareTo
Module m67
Sub Main()
Dim string1 As String = "hello"
Dim string2 As String = "good bye"
Dim string3 As String = "Happy Birthday"
Dim string4 As String = "happy birthday"
'Dim output As String
Dim quotes As Char = ChrW(34)
If (string1.Equals("hello")) Then
Console.WriteLine("string1 equals hello")
Else
Console.WriteLine("not equal ")
End If
' test for equality with =
If string1 = "hello" Then
Console.WriteLine("string1 equals " & quotes &
"hello" & quotes)
Else
Console.WriteLine("string1 does not equal " &
quotes & "hello" & quotes)
End If
If (String.Equals(string3, string4)) Then
Console.WriteLine("string3 equals string4")
Else
25
Console.WriteLine("string3 does not equal
string4")
End If
' test CompareTo
'Console.WriteLine("string1.CompareTo(string2) is " &
_
' string1.CompareTo(string2) & vbCrLf & _
' "string2.CompareTo(string1) is " & _
' string2.CompareTo(string1) & vbCrLf & _
' "string1.CompareTo(string1) is " & _
' string1.CompareTo(string1) & vbCrLf & _
' "string3.CompareTo(string4) is " & _
' string3.CompareTo(string4) & vbCrLf & _
' "string4.CompareTo(string3) is " & _
' string4.CompareTo(string3))
Console.WriteLine("string1.CompareTo(string2) is ",
string1.CompareTo(string2))
'"string2.CompareTo(string1) is " & _
'string2.CompareTo(string1) & vbCrLf & _
'"string1.CompareTo(string1) is " & _
'string1.CompareTo(string1) & vbCrLf & _
'"string3.CompareTo(string4) is " & _
'string3.CompareTo(string4) & vbCrLf & _&
'"string4.CompareTo(string3) is " & _
'string4.CompareTo(string3))
End Sub ' Main
End Module
'Demonstrating StartsWith and EndsWith methods
Module m68
Sub Main()
Dim strings As String()
Dim output As String = ""
Dim i As Integer
Dim quotes As Char = ChrW(34)
strings = New String() {"started", "starting", _
"ended", "ending"}
For i = 0 To strings.GetUpperBound(0)
If strings(i).StartsWith("st") Then
Console.WriteLine(" starts with st")
End If
Next
26
For i = 0 To strings.GetUpperBound(0)
If strings(i).EndsWith("ed") Then
Console.WriteLine(" ends with ed")
End If
Next
End Sub ' Main
End Module
'Replace a sub string with 'Replace'
Class m69
Shared Sub Main()
Dim userInput As String
userInput = " asdf "
Console.WriteLine(Replace(userInput, "f", ""))
End Sub
End Class
'Replace substring with another substring
Public Class m70
Public Shared Sub Main()
Dim s1 As New String("Greeting")
s1 = s1.Replace("e", "i")
Console.WriteLine(s1)
End Sub
End Class
'CInt
Public Class m71
Public Const MAX_VALUES As Integer = CInt(123.45)
Public Shared Sub Main()
End Sub
End Class
'Fix
'Option Strict On
Public Module FixTest
Public Sub Main()
Dim arr() As Decimal = {12.6D, 12.1D, -12.1D, -12.6D}
For Each num As Decimal In arr
Console.WriteLine("Fix({0}): {1}", num, Fix(num))
Console.WriteLine("Int({0}): {1}", num, Int(num))
Console.WriteLine()
Next
End Sub
End Module
27
'Compact operators
Public Class m73
Public Shared Sub Main()
Dim result As New System.Text.StringBuilder
Dim testDouble As Double = Math.PI
result.Append("Double ").AppendLine(testDouble)
testDouble += Math.PI
result.Append("+= ").AppendLine(testDouble)
testDouble *= Math.PI
result.Append("*= ").AppendLine(testDouble)
testDouble -= Math.PI
result.Append("-= ").AppendLine(testDouble)
testDouble /= Math.PI
result.Append("/= ").AppendLine(testDouble)
testDouble ^= Math.PI
result.Append("^= ").AppendLine(testDouble)
result.AppendLine()
Dim testInteger As Integer = 17
result.Append("Integer ").AppendLine(testInteger)
testInteger \= 2
result.Append("\= 2 ... ").AppendLine(testInteger)
testInteger += 1
result.Append("+= 1 ... ").AppendLine(testInteger)
testInteger <<= 1
result.Append("<<= 1 ... ").AppendLine(testInteger)
testInteger >>= 3
result.Append(">>= 3 ... ").AppendLine(testInteger)
result.AppendLine()
Dim testString As String = "Abcdef"
result.Append("String ").AppendLine(testString)
testString &= "ghi"
result.Append("&= ghi ... ").AppendLine(testString)
testString += "jkl"
result.Append("+= jkl ... ").AppendLine(testString)
Console.WriteLine(result.ToString())
End Sub
End Class
28
'Use logic operators in If statement: Not, And, Or
Module M74
Sub Main()
Dim A As Boolean = False
Dim B As Boolean = True
Dim C As Boolean = True
If (Not A) Then
Console.WriteLine("Not A")
End If
If (B Or C) Then
Console.WriteLine("B Or C")
End If
If (B And C) Then
Console.WriteLine("B And C")
End If
End Sub
End Module
'String is Like 'regular expressions *'
Public Class m75
Public Shared Sub Main()
Dim s As String
s = "VB.Net"
If s Like "*VB.Net" Then Console.WriteLine("'VB.Net'
is Like '*VB.Net'")
End Sub
End Class
'String is Like 'regular expressions ?' (question mark)
Public Class m76
Public Shared Sub Main()
Dim s As String
s = "VB.Net"
If s Like "?B.Net" Then Console.WriteLine("'VB.Net' is
Like '?B.Net'")
End Sub
End Class
29
'If with And
Imports System
Public Class m77
Shared Sub Main()
Dim dtCurrent As System.DateTime
Dim iHour As Integer
dtCurrent = Now
iHour = dtCurrent.Hour
If (iHour < 12) Then
Console.Writeline("Good Morning!")
ElseIf (iHour >= 12) And (iHour < 18) Then
Console.WriteLine("Good Afternoon!")
Else
Console.WriteLine("Good Evening!")
End If
End Sub
End Class
'Single line vs Multi-line If statement
Public Class m78
Public Shared Sub Main()
Dim intScore As Integer
intScore = 23
'Single line If statement.
If intScore < 50 Then Console.WriteLine("Failed.") :
Console.WriteLine("Please try again.")
'Multi-line If statement.
If intScore < 50 Then
Console.WriteLine("Failed.")
Console.WriteLine("Please try again.")
End If
End Sub
End Class
30
'IIf
Public Class m79
Public Shared Sub Main()
Dim intScore As Integer
intScore = 23
Console.WriteLine(IIf((intScore < 50), "fail",
"pass"))
End Sub
End Class
'Select Now.DayOfWeek
Public Class m80
Public Shared Sub Main()
Dim strMessage As String
Select Case Now.DayOfWeek
Case DayOfWeek.Monday
strMessage = "Have a nice week."
Case DayOfWeek.Friday
strMessage = "Have a nice weekend."
Case Else
strMessage = "Welcome back!"
End Select
Console.WriteLine(strMessage)
End Sub
End Class
'Use both range and fix value in Select statement
Module M81
Sub Main()
Dim intInput As Integer = 12
Select Case intInput
Case 1
Console.WriteLine("Thank you for the 1.")
Case 2 To 5
Console.WriteLine("Your value was 2, 3, 4, or
5")
Case Is > 5
Console.WriteLine("That was greater than 5.")
Case Else
Console.WriteLine("Sorry, I can't deal with
that.")
End Select
End Sub
End Module
31
'Specify several values in one Case statement
Public Class m82
Public Shared Sub Main()
Select Case "Bird"
Case "Bird"
Console.WriteLine("This animal has 2 legs.")
Case "Horse", "Dog", "Cat"
Console.WriteLine("This animal has 4 legs.")
Case "Snake"
Console.WriteLine("This animal has no legs.")
Case "Centipede"
Console.WriteLine("This animal has 100 legs.")
Case Else
Console.WriteLine("You did not select from the
list!")
End Select
End Sub
End Class
'Select Case statement with String range value
Option Strict On
Imports System
Module M83
Sub Main()
Dim target As String = "M"
Select Case target
Case "A" To "L"
Console.WriteLine("A To L executed")
Case "L" To "Z"
Console.WriteLine("L To Z executed")
Case Else
Console.WriteLine("Else executed")
End Select
End Sub 'Main
End Module
32
'Select Case statement with range Integer value
Option Strict On
Imports System
Module M84
Sub Main()
Dim targetInteger As Integer = 7
Select Case targetInteger
Case Is < 10
Console.WriteLine("Less than 10")
Case 10 To 14
Console.WriteLine("10-14")
Case 15
Console.WriteLine("15!")
Case Else
Console.WriteLine("Value not found")
End Select
End Sub 'Main
End Module
'Microsoft.VisualBasic.Switch
Module M85
Sub Main()
Dim intValue As Integer = -10
Console.WriteLine("Absolute value: " & _
Microsoft.VisualBasic.Switch(intValue < 0, -1 *
intValue, intValue >= 0, intValue))
End Sub
End Module
'For loop with float point control number
Option Strict On
Imports System
Module M86
Sub Main()
Dim loopCounter As Single
For loopCounter = 0.5 To 9
Console.WriteLine("loopCounter: {0}", loopCounter)
Next
End Sub 'Main
33
End Module
'Set For Loop float Step
Option Strict On
Imports System
Module M87
Sub Main()
Dim loopCounter As Single
For loopCounter = 0.5 To 9 Step 0.5
Console.WriteLine("loopCounter: {0}", loopCounter)
Next
End Sub 'Main
End Module
'Use For Each to loop through Array
Option Strict On
Imports System
Public Class Employee3
Private empID As Integer
Public Sub New(ByVal empID As Integer)
Me.empID = empID
End Sub
Public Overrides Function ToString() As String
Return empID.ToString()
End Function
End Class
Class m88
Shared Sub Main()
Dim intArray() As Integer
Dim empArray() As Employee3
intArray = New Integer(5) {}
empArray = New Employee3(3) {}
Dim i As Integer
For i = 0 To empArray.Length - 1
empArray(i) = New Employee3(i + 5)
Next i
Console.WriteLine("The Integer array...")
34
Dim intValue As Integer
For Each intValue In intArray
Console.WriteLine(intValue.ToString())
Next
Console.WriteLine("The employee array...")
Dim e As Employee3
For Each e In empArray
Console.WriteLine(e)
Next
End Sub 'Run
End Class
'Exit For
Public Class m89
Public Shared Sub Main()
Dim j As Integer
For i As Integer = 1 To 3
j = 0
Do While j < 3
j += 1
For k As Integer = 1 To 3
Dim test1 As Boolean = k = 2
If test1 Then Exit For ' Exits the For K
loop.
Dim test2 As Boolean = i = j
If test2 Then Exit Do ' Exits the Do.
Console.WriteLine(i & ", " & j & ", " & k)
Next k
Loop
Next i
End Sub
End Class
'Continue Do
Public Class m90
Public Shared Sub Main()
Dim j As Integer
For i As Integer = 1 To 3
j = 0
Do While j < 3
j += 1
For k As Integer = 1 To 3
Dim test1 As Boolean = k = 2
If test1 Then Continue For ' Continues the
For K loop.
Dim test2 As Boolean = i = j
If test2 Then Continue Do ' Continues the
35
Do.
Console.WriteLine(i & ", " & j & ", " & k)
Next k
Loop
Next i
End Sub
End Class
'GoTo statement with Label
Option Strict On
Imports System
Module M91
Sub Main()
Dim counterVariable As Integer = 0
repeat:
Console.WriteLine("counterVariable: {0}",
counterVariable)
counterVariable += 1
If counterVariable < 10 Then
GoTo repeat
End If
End Sub
End Module
'Imports System
Module m92
Enum Medal As Short
Gold
Silver
Bronze
End Enum
Sub Main()
Dim myMedal As Medal = Medal.Bronze
Console.WriteLine("My medal: " & myMedal.ToString)
End Sub
End Module
'Imports command
Imports System
Public Class Step2
Shared Sub Main()
Console.WriteLine("info")
End Sub
End Class
36
'On Error GoTo errorhandle
Imports System.IO.File
Public Class m94
Public Shared Sub Main()
Dim myfile As System.IO.File
Dim w As System.IO.StreamWriter
On Error GoTo errorhandle
w = myfile.AppendText("a:\temp.txt")
w.Write("a")
w.Close()
Exit Sub
errorhandle:
Console.WriteLine("Please Insert")
Exit Sub
Resume
End Sub
End Class
'Select Case Err.Number
Imports System.IO
Public Class m95
Public Shared Sub Main()
On Error GoTo ErrorHandle
Exit Sub
ErrorHandle:
Select Case Err.Number
Case 52
Console.WriteLine("File Name Exception")
Case 53
Console.WriteLine("File cannot be found")
Case 54
Console.WriteLine("File Mode Exception")
Case 55
Console.WriteLine("File is aleady open")
Case 58
Console.WriteLine("File exists")
Case 68
Console.WriteLine("Device is not available")
37
Case 75
Console.WriteLine("Path Exception")
Case 76
Console.WriteLine("Path cannot be found")
Case Else
Console.WriteLine("Other")
End Select
End Sub
End Class
'Resume
Module M96
Sub Main()
On Error GoTo Handler
Dim i1 As Integer = 0
Dim i2 As Integer = 128
Dim intResult As Integer
intResult = i2 / i1
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
Exit Sub
Handler:
Console.WriteLine("An overflow error occurred.")
Resume Next
End Sub
End Module
'Add Time to current time
Public Class m97
Public Shared Sub Main()
Dim rightNow As Date = Now
Console.WriteLine("RightNow: " & rightNow.ToString)
' ----- Add time values.
Console.WriteLine("RightNow.AddHours(5): " &
rightNow.AddHours(5))
Console.WriteLine("RightNow.AddMinutes(6): " &
rightNow.AddMinutes(6))
Console.WriteLine("RightNow.AddSeconds(7): " &
rightNow.AddSeconds(7))
Console.WriteLine("RightNow.AddMilliseconds(8000): " &
rightNow.AddMilliseconds(8000))
End Sub
End Class
38
'Elapsed Ticks
Public Class m98
Public Shared Sub Main()
Dim ticksBefore As Long
Dim ticksAfter As Long
Dim tickSeconds As Double
ticksBefore = Now.Ticks
MsgBox("Press OK to see elapsed seconds")
ticksAfter = Now.Ticks
tickSeconds = (ticksAfter - ticksBefore) / 10000000.0
Console.WriteLine("Elapsed seconds: " &
tickSeconds.ToString())
End Sub
End Class
'Subtract Time
Public Class m99
Public Shared Sub Main()
Dim results As New System.Text.StringBuilder
Dim rightNow As Date = Now
results.AppendLine("RightNow: " & rightNow.ToString)
results.AppendLine()
results.AppendLine("One year ago: " & _
rightNow.AddYears(-1).ToString)
results.AppendLine("365.25 days ago: " & _
rightNow.AddDays(-365.25).ToString)
Console.WriteLine(results.ToString())
End Sub
End Class
'System Time
39
Public Class m100
Public Shared Sub Main()
Dim rightNow As Date = Now
Dim result As New System.Text.StringBuilder
result.AppendLine("""Now""...")
result.AppendLine()
result.Append("Date:
").AppendLine(rightNow.ToShortDateString)
result.Append("Time:
").AppendLine(rightNow.ToShortTimeString)
result.Append("Ticks:
").Append(rightNow.Ticks.ToString)
Console.WriteLine(result.ToString())
End Sub
End Class
'Date and TimeSpan
Public Class Test
Public Shared Sub Main()
Dim date1 As Date = #7/20/2004#
Dim date2 As Date = #8/21/2004#
Dim elapsed_time As TimeSpan
elapsed_time = Date.op_Subtraction(date2, date1)
Console.WriteLine(elapsed_time.Days.ToString)
End Sub
End Class
'Get Ticks from DateTime
Public Class m102
Public Shared Sub Main()
Console.WriteLine("Ticks since 12:00AM January 1, 1
CE=" + Now().Ticks().ToString())
40
End Sub
End Class
'Compare Date value in If statement
Module M103
Sub Main()
If (Now.Hour < 12) Then
Console.WriteLine("Good morning")
ElseIf (Now.Hour < 18) Then
Console.WriteLine("Good day")
Else
Console.WriteLine("Good evening")
End If
End Sub
End Module
'Select Day Of Week
Module M104
Sub Main()
Dim DayOfWeek As Integer
DayOfWeek = Now.DayOfWeek
Select Case DayOfWeek
Case 1
Console.WriteLine("Sunday")
Case 2
Console.WriteLine("Monday")
Case 3
Console.WriteLine("Tuesday")
Case 4
Console.WriteLine("Wednesday")
41
Case 5
Console.WriteLine("Thursday")
Case 6
Console.WriteLine("Friday")
Case 7
Console.WriteLine("Saturday")
End Select
End Sub
End Module
'Use format specifiers to control the date display
Public Class m105
Public Shared Sub Main()
Dim rightNow As Date = Now
Dim result As New System.Text.StringBuilder
result.AppendLine("""Now""...")
' ----- Use format specifiers to control the date
display.
result.Append("d:
").AppendLine(rightNow.ToString("d"))
result.Append("D:
").AppendLine(rightNow.ToString("D"))
result.Append("t:
").AppendLine(rightNow.ToString("t"))
result.Append("T:
").AppendLine(rightNow.ToString("T"))
result.Append("f:
").AppendLine(rightNow.ToString("f"))
result.Append("F:
").AppendLine(rightNow.ToString("F"))
result.Append("g:
").AppendLine(rightNow.ToString("g"))
result.Append("G:
").AppendLine(rightNow.ToString("G"))
result.Append("M:
").AppendLine(rightNow.ToString("M"))
result.Append("R:
").AppendLine(rightNow.ToString("R"))
result.Append("s:
").AppendLine(rightNow.ToString("s"))
result.Append("u:
42
").AppendLine(rightNow.ToString("u"))
result.Append("U:
").AppendLine(rightNow.ToString("U"))
result.Append("y:
").AppendLine(rightNow.ToString("y"))
Console.WriteLine(result.ToString)
End Sub
End Class
'Date format: dd
Public Class m106
Public Shared Sub Main()
Dim rightNow As Date = Now
Dim result As New System.Text.StringBuilder
result.Append("dd:
").AppendLine(rightNow.ToString("dd"))
Console.WriteLine(result.ToString)
End Sub
End Class
'Date format: ddd
Public Class m107
Public Shared Sub Main()
Dim rightNow As Date = Now
Dim result As New System.Text.StringBuilder
result.Append("ddd:
").AppendLine(rightNow.ToString("ddd"))
Console.WriteLine(result.ToString)
End Sub
End Class
43
'Date format: dddd
Public Class m108
Public Shared Sub Main()
Dim rightNow As Date = Now
Dim result As New System.Text.StringBuilder
result.Append("dddd:
").AppendLine(rightNow.ToString("dddd"))
Console.WriteLine(result.ToString)
End Sub
End Class
'Date format: HH:mm:ss.fff z
Public Class m109
Public Shared Sub Main()
Dim rightNow As Date = Now
Dim result As New System.Text.StringBuilder
result.Append("HH:mm:ss.fff z: ")
result.AppendLine(rightNow.ToString("HH:mm:ss.fff z"))
Console.WriteLine(result.ToString)
End Sub
End Class
'Date format: {0:MMMM-dd-yy HH:mm:ss}
44
Public Class m110
Public Shared Sub Main()
Console.WriteLine(DateTime.Now.ToString)
Console.WriteLine(String.Format("{0:MMMM-dd-yy
HH:mm:ss}", DateTime.Now))
End Sub
End Class
'DateAdd: add two date together
Option Strict On
Public Module DateAddTest
Public Sub Main()
Console.WriteLine(DateAdd(DateInterval.Hour, 36,
Date.Now))
Console.WriteLine(DateAdd(DateInterval.Hour, -36,
Date.Now))
End Sub
End Module
'Different date between two dates
Public Class m112
Public Shared Sub Main()
'Dim dteExpiration As Date
Dim lngDays As Long
lngDays = DateDiff(DateInterval.Day, #12/31/2000#,
Now())
Console.WriteLine(lngDays)
End Sub
End Class
45
'TimeOfDay
Public Class m113
Public Shared Sub Main()
Console.WriteLine(TimeOfDay)
End Sub
End Class
'Different parts of Now
Public Class m114
Public Shared Sub Main()
Dim rightNow As Date = Now
Dim hourNow As Integer = rightNow.Hour
Dim minuteNow As Integer = rightNow.Minute
Dim secondNow As Integer = rightNow.Second
Dim millisecondNow As Integer = rightNow.Millisecond
Dim results As String = String.Format( _
"Hour: {1}{0}Minute: {2}{0}Second: " & _
"{3}{0}Millisecond: {4}", vbNewLine, _
hourNow, minuteNow, secondNow, millisecondNow)
Console.WriteLine(results)
End Sub
End Class
'Use StopWatch
Public Class m115
Public Shared Sub Main()
Dim testWatch As New System.Diagnostics.Stopwatch
Dim results As String
46
' ----- Start counting.
testWatch.Start()
MsgBox("Press OK to see elapsed seconds")
' ----- Stop and record.
results = String.Format( _
"testWatch.Elapsed.Seconds: {0}{3}" & _
"testWatch.Elapsed.TotalSeconds: {1}{3}" & _
"testWatch.ElapsedMilliseconds / 1000: {2}", _
testWatch.Elapsed.Seconds, _
testWatch.Elapsed.TotalSeconds, _
testWatch.ElapsedMilliseconds / 1000, vbNewLine)
Console.WriteLine(results)
End Sub
End Class
'Date different parts
Public Class m116
Public Shared Sub Main()
Dim rightNow As Date = Now
Dim yearNow As Integer = rightNow.Year
Dim monthNow As Integer = rightNow.Month
Dim dayNow As Integer = rightNow.Day
Dim results As String = String.Format( _
"Year: {1}{0}Month: {2}{0}Day: {3}{0}", _
vbNewLine, yearNow, monthNow, dayNow)
Console.WriteLine(results)
End Sub
End Class
'Day of the week
Public Class m117
Public Shared Sub Main()
Console.WriteLine(Today.DayOfWeek.ToString())
End Sub
End Class
47
'TimeSpan and Date Substract
Public Class m118
Public Shared Sub Main()
Dim birthDay As Date
Dim lifeTime As TimeSpan
Dim lifeDays As Integer
birthDay = Date.Parse("December 25, 2007")
lifeTime = Now.Subtract(birthDay)
lifeDays = lifeTime.Days
Console.WriteLine(String.Format( _
"There are {0} days between {1:D} and {2:D}", _
lifeDays, birthDay, Now))
End Sub
End Class
'Define a sub routine and call it
Option Strict On
Imports System
Module m119
Sub Main()
Console.WriteLine("In Main! ")
SomeMethod()
Console.WriteLine("Back in Main( ).")
End Sub 'Main
Sub SomeMethod()
Console.WriteLine("Greetings from SomeMethod!")
End Sub
End Module
'Sub procedure that prints payment information.
48
Module m120
Sub Main()
PrintSub(40, 10.5)
PrintSub(38, 21.75)
PrintSub(20, 13)
PrintSub(50, 14)
End Sub
Sub PrintSub(ByVal hours As Double, ByVal wage As Decimal)
Console.WriteLine("The payment is {0:C}", hours *
wage)
End Sub
End Module
'Define function in a Module
Module M121
Const Sale As Decimal = 100
Const TaxRate As Decimal = 0.04D
Function GetTotalSale() As Decimal
Return Sale * (1 + TaxRate)
End Function
Sub Main()
Dim TotalSale As Decimal = GetTotalSale()
Console.WriteLine(TotalSale)
End Sub
End Module
'Function with string return
49
Public Class m122
Public Shared Sub Main()
Dim strISBN As String = "078212283"
Console.WriteLine("The check Digit is " &
ISBNCheckDigit("078212283") & ".")
Console.WriteLine("The complete ISBN is " & strISBN &
ISBNCheckDigit(strISBN) & ".")
End Sub
Shared Function ISBNCheckDigit(ByVal strISBN As String) As
String
Dim i, intCheckSum, intCheckDigit As Integer
For i = 0 To 8
intCheckSum = intCheckSum + (10 - i) *
strISBN.Substring(i, 1)
Next
intCheckDigit = 11 - (intCheckSum Mod 11)
If intCheckDigit = 10 Then
Return ("X")
Else
Return (intCheckDigit.ToString)
End If
End Function
End Class
'Return double type value from Function
Public Class m123
Public Shared Sub Main()
Console.WriteLine(ComputeSalesTax(34.34, 0.07))
End Sub
Shared Function ComputeSalesTax(ByVal amount As Double, _
ByVal tax As Single) As Double
Return amount * tax
50
End Function
End Class
'Define function and call it in a Module
Module M124
Sub ShowBookInformation()
Console.WriteLine("A")
Console.WriteLine("B")
Console.WriteLine("C")
Console.WriteLine("D")
End Sub
Sub GreetInEnglish()
Console.WriteLine("Hello, world")
End Sub
Sub GreetInSpanish()
Console.WriteLine("Hola, mundo")
End Sub
Sub ShowTime()
Console.WriteLine("Current time is: " & Now)
End Sub
Sub Main()
ShowTime()
GreetInEnglish()
GreetInSpanish()
ShowBookInformation()
End Sub
End Module
'Finds the maximum of three numbers input
51
Module m125
Sub Main()
Dim value1, value2, value3 As Double
value1 = 1.1
value2 = 2.2
value3 = 3.3
Console.WriteLine(Maximum(value1, value2, value3))
End Sub
Function Maximum(ByVal valueOne As Double, _
ByVal valueTwo As Double, ByVal valueThree As Double) _
As Double
Return Math.Max(Math.Max(valueOne, valueTwo),
valueThree)
End Function
End Module
'Optional parameters
Module M126
Sub Main()
ShowMessage()
End Sub
Sub ShowMessage(Optional ByVal strText As String = "Hello
there!")
System.Console.WriteLine(strText)
End Sub
End Module
'Argument Order
52
Imports System
Public Module m127
Public Function Add(ByVal Num1 As Integer, ByVal Num2 As
Double) As Double
Return Num1 + Num2
End Function
Public Function Add(ByVal Num2 As Double, ByVal Num1 As
Integer) As Double
Return Num1 - Num2
End Function
Sub Main()
Dim Num3 As Double = Add(2, 4.2)
Dim Num4 As Double = Add(4.2, 2)
Console.WriteLine("The first Add Method " & Num3)
Console.WriteLine("The Second Add Method " & Num4)
End Sub
End Module
'Demonstrates passing by reference.
Module m128
Sub Main()
Dim number1 As Integer = 2
Console.WriteLine("Before calling SquareByValue, " &
"number1 is {0}", number1)
SquareByValue(number1) ' passes number1 by value
Console.WriteLine("After returning from SquareByValue,
" & "number1 is {0}" & vbCrLf, number1)
Dim number2 As Integer = 2
Console.WriteLine("Before calling SquareByReference, "
& "number2 is {0}", number2)
53
SquareByReference(number2) ' passes number2 by
reference
Console.WriteLine("After returning from " & _
"SquareByReference, number2 is {0}" & vbCrLf,
number2)
Dim number3 As Integer = 2
Console.WriteLine("Before calling SquareByReference "
& "using parentheses, number3 is {0}", number3)
SquareByReference(number3) ' passes number3 by value
Console.WriteLine("After returning from " &
"SquareByReference, number3 is {0}", number3)
End Sub
Sub SquareByValue(ByVal number As Integer)
Console.WriteLine("After entering SquareByValue, " &
"number is {0}", number)
number *= number
Console.WriteLine("Before exiting SquareByValue, " &
"number is {0}", number)
End Sub
Sub SquareByReference(ByRef number As Integer)
Console.WriteLine("After entering SquareByReference" &
", number is {0}", number)
number *= number
Console.WriteLine("Before exiting SquareByReference" &
", number is {0}", number)
End Sub
End Module
'Pass Integer by value to a function
Public Class m129
Public Shared Sub Main()
Dim myInteger As Integer = 5
TestByVal(myInteger)
Console.WriteLine(myInteger)
End Sub
Private Shared Sub TestByVal(ByVal int As Integer)
int = int * 2
End Sub
54
End Class
'Use named parameters
Option Strict On
Public Class Person
Private firstName As String
Private middleName As String
Private lastName As String
Public Sub New(ByVal firstName As String, ByVal middleName
As String, ByVal lastName As String)
Me.firstName = firstName
Me.middleName = middleName
Me.lastName = lastName
End Sub
End Class
Public Module CallingFunctions
Public Sub Main()
Dim person2 As New Person("John", "J.", "Smith")
Dim person1 As New Person(firstName:="John",
lastName:="Smith", middleName:="J.")
End Sub
End Module
'Using ParamArray to create variable-length parameter lists.
Module m131
Sub Main()
AnyNumberArguments()
AnyNumberArguments(2, 3)
AnyNumberArguments(7, 8, 9, 10)
55
End Sub ' Main
Sub AnyNumberArguments(ByVal ParamArray array1 _
As Integer())
Dim i, total As Integer
total = 0
If array1.Length = 0 Then
Console.WriteLine(" received 0 arguments.")
Else
Console.Write("The total of ")
For i = 0 To array1.GetUpperBound(0)
Console.Write(array1(i) & " ")
total += array1(i)
Next
Console.WriteLine("is {0}.", total)
End If
End Sub
End Module
'Recursively generates factorial of number
Public Class m132
Public Shared Sub Main()
Dim value As Integer = 12
Dim i As Integer
For i = 0 To value
Console.WriteLine(i & "! = " & Factorial(i))
Next
End Sub
Shared Function Factorial(ByVal number As Long) As Long
If number <= 1 Then ' base case
Return 1
Else
Return number * Factorial(number - 1)
End If
56
End Function ' Factorial
End Class
'Demonstrating Fibonacci sequence recursively
Public Class m133
Public Shared Sub Main()
Dim number As Integer = 13
Console.WriteLine("Fibonacci Value is " &
Fibonacci(number))
End Sub
' calculate Fibonacci value recusively
Shared Function Fibonacci(ByVal number As Integer) As Long
' check for base cases
If number = 1 OrElse number = 0 Then
Return number
Else
Return Fibonacci(number - 1) + Fibonacci(number -
2)
End If
End Function ' Fibonacci
End Class
'Overloads function
Public Class m134
Public Shared Sub Main()
Console.WriteLine(Min(10.1, 10))
57
Console.WriteLine(Min("last", "first"))
Console.WriteLine(Min(#1/1/2000#, #3/4/2000#))
End Sub
Overloads Shared Function Min(ByVal dblA As Double, ByVal
dblB As Double) As Double
Min = IIf(dblA < dblB, dblA, dblB)
End Function
Overloads Shared Function Min(ByVal strA As String, ByVal
strB As String) As String
Min = IIf(strA < strB, strA, strB)
End Function
Overloads Shared Function Min(ByVal dteA As Date, ByVal
dteB As Date) As Date
Min = IIf(dteA < dteB, dteA, dteB)
End Function
End Class
'Using overloaded methods
Public Class m135
Public Shared Sub Main()
Console.WriteLine("The square of Integer 7 is " & _
Square(7) & vbCrLf & "The square of Double " & _
"7.5 is " & Square(7.5))
End Sub
Shared Function Square(ByVal value As Integer) As Integer
Return Convert.ToInt32(value ^ 2)
End Function ' Square
Shared Function Square(ByVal value As Double) As Double
Return value ^ 2
End Function ' Square
End Class
58
'Using overloaded methods to print arrays of different types
Module m136
Sub Main()
Dim integerArray As Integer() = {1, 2, 3, 4, 5, 6}
Dim doubleArray As Double() = {1.1, 2.2, 3.3, 4.4,
5.5, 6.6, 7.7}
Dim charArray As Char() = {"H"c, "E"c, "L"c, "L"c,
"O"c}
PrintArray(integerArray)
PrintArray(doubleArray)
PrintArray(charArray)
End Sub ' Main
Sub PrintArray(ByVal inputArray() As Integer)
For Each element As Integer In inputArray
Console.Write(element.ToString() & " ")
Next element
Console.WriteLine(vbCrLf)
End Sub
Sub PrintArray(ByVal inputArray() As Double)
For Each element As Double In inputArray
Console.Write(element.ToString() & " ")
Next element
Console.WriteLine(vbCrLf)
End Sub
Sub PrintArray(ByVal inputArray() As Char)
For Each element As Char In inputArray
Console.Write(element.ToString() & " ")
Next element
Console.WriteLine(vbCrLf)
End Sub
End Module
'Method Overloads with different number of parameters
59
Public Class m137
Public Shared Sub Main()
Dim Alerter As New MyMessageBox
Alerter.Alert("No Problems!")
Alerter.Alert("No Problems!", MsgBoxStyle.Exclamation)
End Sub
End Class
Public Class MyMessageBox
Public Sub Alert(ByVal Text As String)
MsgBox(Text)
End Sub
Public Sub Alert(ByVal Text As String, ByVal Icon As
MsgBoxStyle)
MsgBox(Text, Icon)
End Sub
End Class
'Inheritance and overloads
Public Class m138
Public Shared Sub Main()
Dim objBob As New Bob
objBob.Walk("Now I'm walking...")
End Sub
End Class
Public Class Person1
Public Sub Walk()
Console.WriteLine("Walking...")
End Sub
End Class
60
Class Bob
Inherits Person1
Public Overloads Sub Walk(ByVal Text As String)
Console.WriteLine(Text)
End Sub
End Class
'Class with a constructor to initialize its member field value
Module YourClassTest
Sub Main()
Dim obj1 As New YourClass("AAA")
Dim obj2 As New YourClass("BBB")
Console.WriteLine(obj1.YourName)
Console.WriteLine(obj2.YourName)
End Sub ' Main
End Module
Public Class YourClass
Private yourNameValue As String ' course name for this
YourClass
' constructor initializes course name with String supplied
as argument
Public Sub New(ByVal name As String)
YourName = name ' initialize yourNameValue via
property
End Sub ' New
' property YourName
Public Property YourName() As String
Get ' retrieve yourNameValue
Return yourNameValue
End Get
Set(ByVal value As String) ' set yourNameValue
yourNameValue = value ' store the course name in
the object
End Set
61
End Property ' YourName
Public Sub DisplayMessage()
Console.WriteLine("Welcome to " & YourName & "!")
End Sub ' DisplayMessage
End Class ' YourClass
'Class with a constructor to initialize its member field value
Module YourClassTest
Sub Main()
Dim obj1 As New YourClass("AAA")
Dim obj2 As New YourClass("BBB")
Console.WriteLine(obj1.YourName)
Console.WriteLine(obj2.YourName)
End Sub ' Main
End Module
Public Class YourClass
Private yourNameValue As String ' course name for this
YourClass
' constructor initializes course name with String supplied
as argument
Public Sub New(ByVal name As String)
YourName = name ' initialize yourNameValue via
property
End Sub ' New
' property YourName
Public Property YourName() As String
Get ' retrieve yourNameValue
Return yourNameValue
End Get
Set(ByVal value As String) ' set yourNameValue
yourNameValue = value ' store the course name in
the object
End Set
End Property ' YourName
Public Sub DisplayMessage()
62
Console.WriteLine("Welcome to " & YourName & "!")
End Sub ' DisplayMessage
End Class ' YourClass
'Define your own Time Class
Module m142
Sub Main()
Dim time As New CTime() ' call CTime constructor
Console.WriteLine("The initial universal times is: " &
_
time.ToUniversalString() & vbCrLf & _
"The initial standard time is: " & _
time.ToStandardString())
time.SetTime(13, 27, 6) ' set time with valid settings
Console.WriteLine("Universal time after setTime is: "
& _
time.ToUniversalString() & vbCrLf & _
"Standard time after setTime is: " & _
time.ToStandardString())
time.SetTime(99, 99, 99) ' set time with invalid
settings
Console.WriteLine("Universal time: " &
time.ToUniversalString() & _
vbCrLf & "Standard time: " &
time.ToStandardString())
End Sub
End Module
Class CTime
Inherits Object
Private mHour As Integer ' 0 - 23
Private mMinute As Integer ' 0 - 59
Private mSecond As Integer ' 0 - 59
63
Public Sub New()
SetTime(0, 0, 0)
End Sub ' New
Public Sub SetTime(ByVal hourValue As Integer, _
ByVal minuteValue As Integer, ByVal secondValue As
Integer)
If (hourValue >= 0 AndAlso hourValue < 24) Then
mHour = hourValue
Else
mHour = 0
End If
If (minuteValue >= 0 AndAlso minuteValue < 60) Then
mMinute = minuteValue
Else
mMinute = 0
End If
If (secondValue >= 0 AndAlso secondValue < 60) Then
mSecond = secondValue
Else
mSecond = 0
End If
End Sub ' SetTime
' convert String to universal-time format
Public Function ToUniversalString() As String
Return String.Format("{0}:{1:D2}:{2:D2}", _
mHour, mMinute, mSecond)
End Function ' ToUniversalString
' convert to String in standard-time format
Public Function ToStandardString() As String
Dim suffix As String = " PM"
Dim format As String = "{0}:{1:D2}:{2:D2}"
Dim standardHour As Integer
If mHour < 12 Then
suffix = " AM"
End If
If (mHour = 12 OrElse mHour = 0) Then
standardHour = 12
Else
standardHour = mHour Mod 12
End If
Return String.Format(format, standardHour, mMinute, _
64
mSecond) & suffix
End Function
End Class
'Class that contains instance variable and a property to get
and set its value
Module YourClassTest1
Sub Main()
Dim obj As New YourClass2
Console.WriteLine("Initial course name is: " &
obj.YourName & vbCrLf)
obj.YourName = "new Name"
obj.DisplayMessage()
End Sub ' Mains
End Module
Public Class YourClass2
Private yourNameValue As String ' course name for this
YourClass
' property YourName
Public Property YourName() As String
Get ' retrieve yourNameValue
Return yourNameValue
End Get
Set(ByVal value As String) ' set yourNameValue
yourNameValue = value ' store the course name in
the object
End Set
End Property ' YourName
' display a welcome message to the YourClass user
Public Sub DisplayMessage()
Console.WriteLine("Welcome to " & YourName & "!")
End Sub ' DisplayMessage
End Class
'Implement an interface
65
Class YourClass144
Implements IFormattable
Public Value As String
Public Overridable Overloads Function ToString(ByVal _
Format As String, ByVal Provider As IFormatProvider) _
As String Implements IFormattable.ToString
ToString = Value
End Function
Public Sub New(ByVal Value As String)
Me.Value = Value
End Sub
End Class
Module M144
Sub Main()
Dim A As New YourClass("Hello VB.Net World")
Dim S As New String("Hello")
End Sub
End Module
'One Class implements two interfaces
Option Strict On
Imports System
Interface Printable
Sub Read()
Sub Write(ByVal obj As Object)
Property Status() As Integer
66
End Interface 'Printable
Interface Zippable
Sub Zip()
Sub Unzip()
End Interface
Public Class Document
Implements Zippable, Printable
Public Sub New(ByVal s As String)
Console.WriteLine("Creating document with: {0}", s)
End Sub 'New
Public Sub Read() Implements Printable.Read
Console.WriteLine("Implementing the Read Method for
Printable")
End Sub 'Read
Public Sub Write(ByVal o As Object) Implements
Printable.Write
Console.WriteLine( _
"Implementing the Write Method for Printable")
End Sub 'Write
Public Property Status() As Integer Implements
Printable.Status
Get
Return myStatus
End Get
Set(ByVal Value As Integer)
myStatus = Value
End Set
End Property
Public Sub Zip() Implements Zippable.Zip
Console.WriteLine("Implementing Zip")
End Sub
Public Sub Unzip() Implements Zippable.Unzip
Console.WriteLine("Implementing Unzip")
End Sub
Private myStatus As Integer = 0
End Class
Class m145
Shared Sub Main()
Dim doc As New Document("Test Document")
doc.Status = -1
doc.Read()
67
doc.Zip()
Console.WriteLine("Document Status: {0}", doc.Status)
End Sub 'Main
End Class
'Inheritance And Interfaces
Imports System
Imports System.Collections
Public Interface Printable1
ReadOnly Property Print() As Integer
End Interface
Public Class Money
Implements Printable1
Protected mTransactions As New ArrayList()
ReadOnly Property Print() As Integer Implements
Printable1.Print
Get
Return mTransactions.Count
End Get
End Property
Public Overridable ReadOnly Property Balance() As Double
Get
Dim result As Double = 0.0
Dim i As Integer
For i = 0 To mTransactions.Count - 1
result += CDbl(mTransactions(i))
Next
Return result
End Get
End Property
Public Sub Add(ByVal amount As Double)
mTransactions.Add(amount)
End Sub
Public Sub Subtract(ByVal amount As Double)
mTransactions.Add(-amount)
End Sub
68
End Class
Public Class MyMoney
Inherits Money
Public Overrides ReadOnly Property Balance() As Double
Get
Return MyBase.Balance - Print * 2
End Get
End Property
End Class
Module m146
Sub Main()
Dim acc1 As New Money()
acc1.Add(200)
acc1.Subtract(40)
acc1.Add(30)
Console.Write("count: {0}, ", acc1.Print)
Console.WriteLine("balance: {0}", acc1.Balance)
Dim acc2 As New MyMoney()
acc2.Add(200)
acc2.Subtract(40)
acc2.Add(30)
Console.Write("count: {0}, ", acc2.Print)
Console.WriteLine("balance: {0}", acc2.Balance)
End Sub
End Module
'Reimplement interface
Class BaseClass
Implements IFormattable
Implements IComparable
Public Value As String
Public Overridable Overloads Function ToString(ByVal _
Format As String, ByVal Provider As IFormatProvider) _
69
As String Implements IFormattable.ToString
ToString = Value
End Function
Public Overridable Overloads Function CompareTo(ByVal A _
As Object) As Integer Implements IComparable.CompareTo
If (Value = A.Value) Then
CompareTo = 0
ElseIf (Value < A.Value) Then
CompareTo = -1
Else
CompareTo = 1
End If
End Function
Public Sub New(ByVal Value As String)
Me.Value = Value
End Sub
End Class
Class DerivedClass
Inherits BaseClass
Public Overrides Function ToString(ByVal _
Format As String, ByVal Provider As IFormatProvider) _
As String
ToString = UCase(Value)
End Function
Public Sub New(ByVal Value As String)
MyBase.New(Value)
End Sub
End Class
Module M147
Sub Main()
Dim A As New BaseClass("Hello")
Dim B As New DerivedClass("Hi")
Console.WriteLine(A)
Console.WriteLine(B)
Console.WriteLine(A.CompareTo(B))
End Sub
End Module
70
'Public Sub aMethod() Implements Interface1.Method,
Interface2.Method
Public Interface I1
Sub Draw()
End Interface
Public Interface I2
Sub Draw()
End Interface
Public Class Class1
Implements I1, I2
Public Sub foo() Implements I1.Draw, I2.Draw
End Sub
End Class
'Two classes implement one interface
Public Class m149
Public Shared Sub Main()
Dim rect As New Rectangle()
Dim trap As New Trapezoid()
rect.Draw()
trap.Draw()
End Sub
End Class
Public Interface IShape
Function Draw() As String
End Interface
Public Class Rectangle
Implements IShape
Public Function Draw() As String Implements IShape.Draw
Return "Drawing Rectangle"
End Function
End Class
Public Class Trapezoid
Implements IShape
Public Function Draw() As String Implements IShape.Draw
71
Return "Drawing Trapezoid"
End Function
End Class
'Shadow member variable in base class
Module M150
Class BaseClass
Public Name As String
Public Amount As Integer
Public Message As String
Public Sub New(ByVal Name As String, ByVal Amount As
Integer, ByVal Message As String)
Me.Name = Name
Me.Amount = Amount
Me.Message = Message
End Sub
Public Sub ShowBaseMembers()
Console.WriteLine("Name: " & Name)
Console.WriteLine("Amount: " & Amount)
Console.WriteLine("Message: " & Message)
End Sub
End Class
Class DerivedClass
Inherits BaseClass
' Public Amount As Double
Public Shadows Message As String
Public Sub ShowDerivedMembers()
Console.WriteLine("Name: " & Name)
Console.WriteLine("Amount: " & Amount)
Console.WriteLine("Message: " & Message)
End Sub
Public Sub New(ByVal Name As String, ByVal Amount As
Integer, ByVal Message As String)
MyBase.New(Name, Amount, Message)
End Sub
72
End Class
Sub Main()
End Sub
End Module
'Method with parameter
Option Strict On
Imports System
Public Class TestClass
Sub SomeMethod(ByVal firstParam As Integer, ByVal
secondParam As Single)
Console.WriteLine("received: {0}, {1}", firstParam,
secondParam)
End Sub
End Class
Module M151
Sub Main()
Dim howManyPeople As Integer = 5
Dim pi As Single = 3.14F
Dim tc As New TestClass()
tc.SomeMethod(howManyPeople, pi)
End Sub
End Module
'Simple Inheritance
Public Class m152
73
Public Shared Sub Main()
Dim objJohn As New John1
objJohn.Walk()
End Sub
End Class
Public Class ok
Public Sub Walk()
Console.WriteLine("Walking...")
End Sub
End Class
Class John1
Inherits ok
End Class
'Multilevel inheritance
Class Person11
Public Name As String
Public Age As Integer
Public Sub New(ByVal Name As String, ByVal Age As Integer)
Me.Name = Name
Me.Age = Age
End Sub
End Class
Class Player
Inherits Person11
Public Sport As String
Public Team As String
Public Sub New(ByVal Name As String, ByVal Age As Integer,
_
ByVal Sport As String, ByVal Team As String)
MyBase.New(Name, Age)
Me.Team = Team
Me.Sport = Sport
End Sub
End Class
Class BasketPlayer
74
Inherits Player
Public PointsPerGame As Double
Public Rebounds As Double
Public Sub New(ByVal Name As String, ByVal Age As Integer,
_
ByVal Sport As String, ByVal Team As String, ByVal Points
As Double, ByVal Rebounds As Double)
MyBase.New(Name, Age, Sport, Team)
Me.PointsPerGame = Points
Me.Rebounds = Rebounds
End Sub
Public Sub Show()
Console.WriteLine("Player: " & Name)
Console.WriteLine("Age: " & Age)
Console.WriteLine("Sport: " & Sport)
Console.WriteLine("Team: " & Team)
Console.WriteLine("Points: " & PointsPerGame)
Console.WriteLine("Rebounds: " & Rebounds)
End Sub
End Class
Module M153
Sub Main()
Dim K As New BasketPlayer("AA", 12, "Basketball",
"Team", 25.5, 6.3)
K.Show()
End Sub
End Module
'Polymorphic Behaviour
Class ID
Public Number As String
Public Sub New(ByVal Number As String)
Me.Number = Number
End Sub
Public Overridable Sub Dial()
75
Console.WriteLine("Dialing: " & Number)
End Sub
End Class
Class Phone
Inherits ID
Public Sub New(ByVal Number As String)
MyBase.New(Number)
End Sub
Public Overrides Sub Dial()
Console.WriteLine("Beep, touch-tone phone calling: " &
Number)
End Sub
End Class
Class CreditCardID
Inherits ID
Public Sub New(ByVal Number As String)
MyBase.New(Number)
End Sub
Public Overrides Sub Dial()
Console.WriteLine("Rotary dialing: " & Number)
End Sub
End Class
Module M154
Sub Main()
Dim card As New CreditCardID("555-1212")
Dim phone As New Phone("800-555-1212")
Dim PolyID As ID
Console.WriteLine("Using standard objects")
card.Dial()
phone.Dial()
Console.WriteLine("Using polymorphic phone")
PolyID = card
PolyID.Dial()
PolyID = phone
PolyID.Dial()
End Sub
End Module
76
'Late binding
Public Class m155
Public Shared Sub Main()
Dim objHorse As Object
Dim objPuma As Object
objHorse = New Horse
objPuma = New Puma
Try
objHorse.Walk()
Catch
Console.WriteLine("Sorry, no Walk method available
in objHorse.")
End Try
Try
objPuma.Walk()
Catch
Console.WriteLine("Sorry, no Walk method available
in objPuma.")
End Try
End Sub
End Class
Public Class Horse
Public Sub Walk()
Console.WriteLine("Walking...")
End Sub
End Class
Public Class Puma
Public Sub Run()
Console.WriteLine("Running...")
End Sub
End Class
'Inherits' must be first line. There can be only one
77
Public Class P
Inherits System.Object
Public Name As String
Public Birthday As Date
End Class
Public Class Student
Inherits P
Public Sub New(ByVal StudentName As String, ByVal
BirthDate As Date)
MyBase.Name = StudentName
MyBase.Birthday = BirthDate
End Sub
Public StudentID
Public Overrides Function ToString() As String
Return (Me.Name)
End Function
End Class
'Call Shared method
Option Strict On
Imports System
Class YourCl
Private Shared instances As Integer = 0
Private weight As Integer
Private name As String
Public Sub New(ByVal name As String, ByVal weight As
Integer)
instances += 1
Me.name = name
Me.weight = weight
End Sub
Public Shared Sub SharedMerthod()
Console.WriteLine("{0} cats adopted", instances)
End Sub
Public Sub TellWeight()
Console.WriteLine("{0} is {1} pounds", name, weight)
End Sub
78
End Class
Module M157
Sub Main()
YourCl.SharedMerthod()
Dim obj As New YourCl("A", 5)
obj.TellWeight()
YourCl.SharedMerthod()
Dim obj2 As New YourCl("B", 7)
obj2.TellWeight()
YourCl.SharedMerthod()
YourCl.SharedMerthod()
End Sub
End Module
'Shared field
Public Class m158
Public Shared Sub Main()
Dim Counter1 As New Counter
Dim Counter2 As New Counter
Console.WriteLine("Total count = " & Counter1.Count())
Console.WriteLine("Total count = " & Counter2.Count())
Console.WriteLine("Total count = " & Counter1.Count())
Console.WriteLine("Total count = " & Counter2.Count())
Console.WriteLine("Total count = " & Counter1.Count())
Console.WriteLine("Total count = " & Counter2.Count())
Console.WriteLine("Total count = " & Counter1.Count())
Console.WriteLine("Total count = " & Counter2.Count())
End Sub
End Class
Public Class Counter
Shared Data As Integer = 0
Public Function Count() As Integer
Data += 1
Return Data
End Function
End Class
79
'Class with Private fields and Public method
Imports System
Public Class Time
' Private variables
Private Year As Integer
Private Month As Integer
Private Hour As Integer
Private Minute As Integer
Private Second As Integer
' Public methods
Public Sub DisplayCurrentTime()
Console.WriteLine("stub for DisplayCurrentTime")
End Sub 'DisplayCurrentTime
End Class 'Time
Module M159
Sub Main()
Dim timeObject As New Time()
timeObject.DisplayCurrentTime()
End Sub
End Module
'Define delegate
Public Class m160
Private Delegate Function NumEmployeesDelegate() As
Integer
Private Delegate Function GetNameDelegate() As String
Public Shared Sub Main()
Dim emp As New Employee()
Dim show_name As GetNameDelegate
show_name = AddressOf emp.ToString
Console.WriteLine(show_name())
80
End Sub
End Class
Public Class Employee
Public Shared Function GetNumEmployees() As Integer
Return 13
End Function
Public Overrides Function ToString() As String
Return "Employee"
End Function
End Class
'Delegate Function
Module M161
Delegate Function Numbers(ByVal A As Double, ByVal B As
Double) As Double
Function SubtractNumbers(ByVal A As Double, ByVal B As
Double) As Double
SubtractNumbers = A - B
End Function
Function AddNumbers(ByVal A As Double, ByVal B As Double)
As Double
AddNumbers = A + B
End Function
Sub Main()
Dim DoNumbers As New Numbers(AddressOf
SubtractNumbers)
Console.WriteLine(DoNumbers.Invoke(100, 50))
DoNumbers = AddressOf AddNumbers
Console.WriteLine(DoNumbers.Invoke(100, 50))
End Sub
End Module
81
'Uses delegates to sort random numbers (ascending or
descending)
Public Class m162
Private Shared Function SortAscending(ByVal element1 As
Integer, _
ByVal element2 As Integer) As Boolean
Return element1 > element2
End Function ' SortAscending
Private Shared Function SortDescending(ByVal element1 As
Integer, _
ByVal element2 As Integer) As Boolean
Return element1 < element2
End Function ' SortDescending
Public Shared Sub Main()
Dim mBubbleSort As New BubbleSort()
Dim mElementArray As Integer() = New Integer(9) {}
Dim randomNumber As Random = New Random()
Dim i As Integer
' create String with 10 random numbers
For i = 0 To mElementArray.GetUpperBound(0)
mElementArray(i) = randomNumber.Next(100)
Console.WriteLine(mElementArray(i))
Next
mBubbleSort.SortArray(mElementArray, AddressOf
SortAscending)
For i = 0 To mElementArray.GetUpperBound(0)
Console.Write(mElementArray(i) & " ")
Next
Console.WriteLine()
mBubbleSort.SortArray(mElementArray, AddressOf
SortDescending)
For i = 0 To mElementArray.GetUpperBound(0)
Console.Write(mElementArray(i) & " ")
Next
End Sub
82
End Class
Public Class BubbleSort
Public Delegate Function Comparator( _
ByVal element1 As Integer, _
ByVal element2 As Integer) As Boolean
Public Sub SortArray(ByVal array As Integer(), _
ByVal Compare As Comparator)
Dim i, pass As Integer
For pass = 0 To array.GetUpperBound(0)
For i = 0 To array.GetUpperBound(0) - 1
If Compare(array(i), array(i + 1)) Then
Swap(array(i), array(i + 1))
End If
Next ' inner loop
Next ' outer loop
End Sub ' SortArray
Private Sub Swap(ByRef firstElement As Integer, _
ByRef secondElement As Integer)
Dim hold As Integer
hold = firstElement
firstElement = secondElement
secondElement = hold
End Sub ' Swap
End Class
'Multiple Delegates
Module M163
Delegate Sub NotifyInfo()
Dim ListOfDelegates(3) As NotifyInfo
Sub Testing()
Console.WriteLine("AAA")
End Sub
Sub Coding()
83
Console.WriteLine("BBB")
End Sub
Sub Meeting()
Console.WriteLine("CCC")
End Sub
Sub Main()
ListOfDelegates(0) = New NotifyInfo(AddressOf Coding)
ListOfDelegates(1) = New NotifyInfo(AddressOf Testing)
ListOfDelegates(2) = New NotifyInfo(AddressOf Meeting)
Dim NotifyAll As New NotifyInfo(AddressOf Coding)
NotifyAll = NotifyInfo.Combine(ListOfDelegates)
NotifyAll.Invoke()
End Sub
End Module
'Friend members are available to any object in the same
assembly (Friend is referred to as internal in C#)
Public Class SomeClassInMyAssembly
Friend vFriend As Integer
End Class
'Class with constructor
Option Strict On
Imports System
Public Class Time1
' Private variables
84
Private Year As Integer
Private Month As Integer
Private mDate As Integer
Private Hour As Integer
Private Minute As Integer
Private Second As Integer
' Public methods
Public Sub DisplayCurrentTime()
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
Month, mDate, Year, Hour, Minute, Second)
End Sub 'DisplayCurrentTime
' Constructor
Public Sub New(ByVal theYear As Integer, ByVal theMonth As
Integer, _
ByVal theDate As Integer, ByVal theHour As
Integer, _
ByVal theMinute As Integer, ByVal theSecond
As Integer)
Year = theYear
Month = theMonth
mDate = theDate
Hour = theHour
Minute = theMinute
Second = theSecond
End Sub
End Class 'Time
Module Module166
Sub Main()
Dim timeObject As New Time1(2005, 3, 25, 9, 35, 20)
timeObject.DisplayCurrentTime()
End Sub
End Module
'Empty constructor
Imports System
Module m167
85
Sub Main()
Dim p1 As New Point()
Dim p2 As New Point(100, 100)
Console.WriteLine(p1)
Console.WriteLine(p2)
End Sub
End Module
Class Point
Private X As Integer
Private Y As Integer
Sub New()
End Sub
Sub New(ByVal x As Integer, ByVal y As Integer)
Me.X = x
Me.Y = y
End Sub
Public Overrides Function ToString() As String
Return ("(" & X & "," & Y & ")")
End Function
End Class
'Default constructor
Imports System
Module m168
Sub Main()
Dim p1 As New Point1()
Dim p2 As New Point1()
p2.Y = 100
p2.X = 100
Console.WriteLine(p1)
Console.WriteLine(p2)
End Sub
End Module
Class Point1
Public X As Integer
Public Y As Integer
86
Public Overrides Function ToString() As String
Return ("(" & X & "," & Y & ")")
End Function
End Class
'Copy constructor
Option Strict On
Imports System
Public Class Time2
' Private variables
Private Year As Integer
Private Month As Integer
Private mDate As Integer
Private Hour As Integer
Private Minute As Integer
Private Second As Integer = 30
' Public methods
Public Sub DisplayCurrentTime()
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", _
Month, mDate, Year, Hour, Minute, Second)
End Sub 'DisplayCurrentTime
Public Sub New( _
ByVal theYear As Integer, _
ByVal theMonth As Integer, _
ByVal theDate As Integer, _
ByVal theHour As Integer, _
ByVal theMinute As Integer)
Year = theYear
Month = theMonth
mDate = theDate
Hour = theHour
Minute = theMinute
End Sub
Public Sub New(ByVal existingObject As Time2)
Year = existingObject.Year
Month = existingObject.Month
mDate = existingObject.mDate
Hour = existingObject.Hour
Minute = existingObject.Minute
Second = existingObject.Second
87
End Sub
End Class 'Time
Module Module169
Sub Main()
Dim timeObject As New Time2(2005, 3, 25, 9, 35)
Dim t2 As New Time2(timeObject)
timeObject.DisplayCurrentTime()
t2.DisplayCurrentTime()
End Sub
End Module
'Constructors in three levels
Class A
Public Sub New()
Console.WriteLine("In class A constructor")
End Sub
End Class
Class B
Inherits A
Public Sub New()
Console.WriteLine("In class B constructor")
End Sub
End Class
Class C
Inherits B
Public Sub New()
Console.WriteLine("In class C constructor")
End Sub
End Class
Module Module170
Sub Main()
Dim objSample As New C()
End Sub
End Module
88
'Overloaded constructors
Module m171
Sub Main()
' use overloaded constructors
Dim time1 As New MyTime()
Dim time2 As New MyTime(2)
Dim time3 As New MyTime(21, 34)
Dim time4 As New MyTime(12, 25, 42)
Dim time5 As New MyTime(27, 74, 99)
Dim time6 As New MyTime(time4) ' use time4 as initial
value
Console.WriteLine(time1.ToUniversalString())
Console.WriteLine(time2.ToUniversalString())
Console.WriteLine(time3.ToUniversalString())
Console.WriteLine(time4.ToUniversalString())
Console.WriteLine(time5.ToUniversalString())
Console.WriteLine(time6.ToUniversalString())
End Sub ' Main
End Module
Class MyTime
Inherits Object
Private mHour As Integer ' 0 - 23
Private mMinute As Integer ' 0 - 59
Private mSecond As Integer ' 0 - 59
Public Sub New()
SetTime()
End Sub ' New
Public Sub New(ByVal hourValue As Integer)
SetTime(hourValue)
End Sub ' New
89
Public Sub New(ByVal hourValue As Integer, _
ByVal minuteValue As Integer)
SetTime(hourValue, minuteValue)
End Sub ' New
Public Sub New(ByVal hourValue As Integer, _
ByVal minuteValue As Integer, ByVal secondValue As
Integer)
SetTime(hourValue, minuteValue, secondValue)
End Sub ' New
Public Sub New(ByVal timeValue As MyTime)
SetTime(timeValue.mHour, timeValue.mMinute,
timeValue.mSecond)
End Sub ' New
Public Sub SetTime(Optional ByVal hourValue As Integer =
0, _
Optional ByVal minuteValue As Integer = 0, _
Optional ByVal secondValue As Integer = 0)
If (hourValue >= 0 AndAlso hourValue < 24) Then
mHour = hourValue
Else
mHour = 0
End If
If (minuteValue >= 0 AndAlso minuteValue < 60) Then
mMinute = minuteValue
Else
mMinute = 0
End If
If (secondValue >= 0 AndAlso secondValue < 60) Then
mSecond = secondValue
Else
mSecond = 0
End If
End Sub ' SetTime
Public Function ToUniversalString() As String
Return String.Format("{0}:{1:D2}:{2:D2}", _
mHour, mMinute, mSecond)
End Function ' ToUniversalString
End Class
90
'Call member method in constructor
Option Strict On
Public Class Counters
Dim ctr As Integer
Public Sub New()
For ctr = 1 To 20
DoSomething()
Next
End Sub
Public Sub DoSomething()
Console.WriteLine(Me.ctr)
End Sub
End Class
Public Module modMain
Public Sub Main()
Dim obj As New Counters()
End Sub
End Module
'Inheriting Constructors
Public Class Test1
Public Shared Sub Main()
Dim objJohn As New John("Walking...")
objJohn.Walk()
End Sub
End Class
Public Class Person5
Private Text As String
Public Sub New(ByVal Message As String)
Text = Message
91
End Sub
Public Sub Walk()
Console.WriteLine(Text)
End Sub
End Class
Class John
Inherits Person5
Public Sub New(ByVal Message As String)
MyBase.New(Message)
End Sub
End Class
'Shared Constructor
Public Class YourClass175
Private Shared ID As Integer = 10
Public Shared ReadOnly Property CurrentID() As Integer
Get
Return ID
End Get
End Property
Public Shared Function GetID() As Integer
ID += 1
Return ID
End Function
Shared Sub New()
Console.WriteLine("Before init: " & ID)
ID = 100
Console.WriteLine("After init: " & ID)
End Sub
End Class
Module m175
Sub Main()
Dim CountValue As Integer
For CountValue = 1 To 10
Console.WriteLine(YourClass175.GetID())
Next
End Sub
92
End Module
'Constructor with Optional parameter
Public Class Point2
Private MX As Integer
Private MY As Integer
Public Sub New(Optional ByVal X As Integer = 0, Optional
ByVal Y As Integer = 0)
MX = X
MY = Y
End Sub
Public Overrides Function ToString() As String
Return "(" & MX & "," & MY & ")"
End Function
End Class
Module OptionalPoint
Sub Main()
Dim P1 As New Point2()
Console.WriteLine(P1.ToString())
Dim P2 As New Point2(1, 1)
Console.WriteLine(P2.ToString())
Dim P3 As New Point2(, 1)
Console.WriteLine(P3.ToString())
Dim P4 As New Point2(9, )
Console.WriteLine(P4.ToString())
End Sub
End Module
'Constructor Chain
93
Public Class YourClass177
Public Address As String = "Default"
Public City As String = "Default"
Sub New()
MyBase.New()
Console.WriteLine("YourClass Created")
End Sub
Sub New(ByVal A As String, ByVal C As String)
Me.New()
Address = A
City = C
Console.WriteLine("YourClass.Address and Set")
End Sub
End Class
Module m177
Sub Main()
Dim SL As New YourClass177("123 First Street",
"Somewhere")
End Sub
End Module
'constructor inheriting
Public Class Address
Private MyState As String = "DEFAULT"
Sub New()
MyBase.New()
Console.WriteLine("Address Created")
End Sub
Public Property State() As String
Get
Return MyState
End Get
Set(ByVal Value As String)
MyState = Value
94
End Set
End Property
End Class
Public Class MyAddress
Inherits Address
Private MyAddress As String
Sub New()
MyBase.New()
Console.WriteLine("MyAddress Created")
End Sub
Public Property Address() As String
Get
Return MyAddress
End Get
Set(ByVal Value As String)
MyAddress = Value
End Set
End Property
End Class
Module Test178
Sub Main()
Dim SL As New MyAddress()
SL.State = "CANADA"
SL.Address = "123"
End Sub
End Module
'Destructor in three levels
Class A5
Public Sub New()
Console.WriteLine("In class A constructor")
End Sub
Protected Overrides Sub Finalize()
Console.WriteLine("In class A destructor")
MyBase.Finalize()
End Sub
95
End Class
Class B5
Inherits A5
Public Sub New()
Console.WriteLine("In class B constructor")
End Sub
Protected Overrides Sub Finalize()
Console.WriteLine("In class B destructor")
MyBase.Finalize()
End Sub
End Class
Class C5
Inherits B5
Public Sub New()
Console.WriteLine("In class C constructor")
End Sub
Protected Overrides Sub Finalize()
Console.WriteLine("In class C destructor")
MyBase.Finalize()
End Sub
End Class
Module Module179
Sub Main()
Dim objSample As New C5()
End Sub
End Module
'Inherit destructor
Class Base
Public Sub New()
Console.WriteLine("The Base Class Constructor is
Running")
End Sub
Protected Overrides Sub Finalize()
Console.WriteLine("The Base Class Destructor is
96
Running")
MyBase.Finalize()
End Sub
End Class
Class Derived
Inherits Base
Public Sub New()
Console.WriteLine("The Derived Class Constructor is
Running")
End Sub
Protected Overrides Sub Finalize()
Console.WriteLine("The Derived Class Destructor is
Running")
MyBase.Finalize()
End Sub
End Class
Module Module180
Sub Main()
Dim Sample As New Derived()
End Sub
End Module
'Call constroctor from base class
Option Strict On
Imports System
Public Class Rectangle11
Public Sub New(ByVal top As Integer, ByVal left As
Integer)
Me.top = top
Me.left = left
End Sub
Public Sub DrawRectangle()
Console.WriteLine("Drawing Rectangle at {0}, {1}",
top, left)
End Sub
Private top As Integer
Private left As Integer
97
End Class
Public Class NamedRectangle
Inherits Rectangle11
Public Sub New(ByVal top As Integer, ByVal left As
Integer, ByVal n As String)
MyBase.New(top, left)
RectName = n
End Sub 'New
Public Shadows Sub DrawRectangle()
MyBase.DrawRectangle()
Console.WriteLine("Writing string to the listbox:
{0}", RectName)
End Sub
Private RectName As String
End Class
Module Module181
Sub Main()
Dim w As New Rectangle11(5, 10)
w.DrawRectangle()
Dim lb As New NamedRectangle(20, 30, "Hello")
lb.DrawRectangle()
End Sub
End Module
'Call method with MyBase
Option Strict On
Imports System
Public Class Control
Public Sub New(ByVal top As Integer, ByVal left As
Integer)
Me.top = top
Me.left = left
End Sub
Public Overridable Sub DrawControl()
Console.WriteLine("Control: drawing Control at {0},
98
{1}", top, left)
End Sub
Protected top As Integer
Protected left As Integer
End Class
Public Class Label
Inherits Control
Public Sub New(ByVal top As Integer, ByVal left As
Integer, ByVal n As String)
MyBase.New(top, left)
text = n
End Sub
Public Overrides Sub DrawControl()
MyBase.DrawControl()
Console.WriteLine("Writing string to the listbox:
{0}", text)
End Sub
Private text As String
End Class
Public Class Button
Inherits Control
Public Sub New(ByVal top As Integer, ByVal left As
Integer)
MyBase.New(top, left)
End Sub 'New
Public Overrides Sub DrawControl()
Console.WriteLine("Drawing a button at {0}, {1}" +
ControlChars.Lf, top, Left)
End Sub
End Class
Public Class Tester182
Shared Sub Main()
Dim win As New Control(1, 2)
Dim lb As New Label(3, 4, "test")
Dim b As New Button(5, 6)
win.DrawControl()
lb.DrawControl()
b.DrawControl()
Dim winArray(3) As Control
99
winArray(0) = New Control(1, 2)
winArray(1) = New Label(3, 4, "AAA")
winArray(2) = New Button(5, 6)
Dim i As Integer
For i = 0 To 2
winArray(i).DrawControl()
Next i
End Sub
End Class
'Override ToString method
Option Strict On
Imports System
Public Class Dog
Private weight As Integer
Public Sub New(ByVal weight As Integer)
Me.weight = weight
End Sub
Public Overrides Function ToString() As String
Return weight.ToString()
End Function
End Class
Public Class Tester183
Shared Sub Main()
Dim i As Integer = 5
Console.WriteLine(i.ToString())
Dim milo As New Dog(62)
Console.WriteLine(milo.ToString())
End Sub
End Class
'Assign string value to an Object variable
100
Public Class Test184
Public Shared Sub Main()
Dim objMyModemSpeed As Object
objMyModemSpeed = "28.8"
Console.WriteLine(objMyModemSpeed)
Console.WriteLine(objMyModemSpeed * 1000 / 8)
objMyModemSpeed = Nothing
End Sub
End Class
'Create an object and call its method.
Module YourClassTest185
Sub Main()
Dim obj As New YourClass11()
obj.DisplayMessage()
End Sub
End Module
Public Class YourClass11
Public Sub DisplayMessage()
Console.WriteLine("Welcome!")
End Sub
End Class
'Sort objects in an array
Imports System.Collections
Public Class Test186
Public Shared Sub Main()
101
Dim people(4) As Employee1
people(0) = New Employee1("R", "S")
people(1) = New Employee1("S", "A")
people(2) = New Employee1("T", "P")
people(3) = New Employee1("H", "S")
people(4) = New Employee1("E", "C")
' Sort.
Array.Sort(people)
For i As Integer = 0 To people.GetUpperBound(0)
Console.WriteLine(people(i).ToString())
Next i
End Sub
End Class
Public Class Employee1
Implements IComparable
Public FirstName As String
Public LastName As String
Public Sub New(ByVal first_name As String, ByVal last_name
As String)
FirstName = first_name
LastName = last_name
End Sub
Public Overrides Function ToString() As String
Return LastName & ", " & FirstName
End Function
Public Function CompareTo(ByVal obj As Object) As Integer
_
Implements System.IComparable.CompareTo
Dim other_Employee As Employee = DirectCast(obj,
Employee)
Return String.Compare(Me.ToString,
other_Employee.ToString)
End Function
End Class
'Define and use a Property
Option Strict On
102
Imports System
Public Class Cat
Private mWeight As Integer
Public Sub New(ByVal weight As Integer)
mWeight = weight
End Sub
Public Property Weight() As Integer
Get
Return mWeight
End Get
Set(ByVal Value As Integer)
mWeight = Value
End Set
End Property
Public Overrides Function ToString() As String
Return mWeight.ToString()
End Function
End Class
Module Module187
Sub Main()
Dim theVariable As New Cat(5)
Console.WriteLine("In Run. theVariable: {0}",
theVariable)
Doubler(theVariable)
Console.WriteLine("Back in Run. theVariable: {0}",
theVariable)
End Sub
Public Sub Doubler(ByVal param As Cat)
Console.WriteLine("In Method1. Received param: {0}",
param)
param.Weight = param.Weight * 2
Console.WriteLine("Updated param. Returning new value:
{0}", param)
End Sub
End Module
103
'Use MustInherit to define abstract class
Public MustInherit Class Printable2
Public PageData As String
Public MustOverride Sub ShowPage()
Public Sub New(ByVal Message As String)
PageData = Message
End Sub
End Class
Public Class Word
Inherits Printable2
Public Overrides Sub ShowPage()
Console.WriteLine("word: " & PageData)
End Sub
Public Sub New(ByVal Message As String)
MyBase.New(Message)
End Sub
End Class
Public Class Text
Inherits Printable2
Public Overrides Sub ShowPage()
Console.WriteLine("Test: " & PageData)
End Sub
Public Sub New(ByVal Message As String)
MyBase.New(Message)
End Sub
End Class
Module Module188
Sub Main()
Dim WebPage As Word = New Word("word page")
104
Dim MobilePage As Text = New Text("text file")
WebPage.ShowPage()
Console.WriteLine()
MobilePage.ShowPage()
End Sub
End Module
'MustInherit class
Option Strict On
Imports System
Public MustInherit Class Control1
Public Sub New(ByVal top As Integer, ByVal left As
Integer)
Me.top = top
Me.left = left
End Sub
Public MustOverride Sub DrawControl()
Protected top As Integer
Protected left As Integer
End Class
Public Class Label1
Inherits Control1
Public Sub New(ByVal top As Integer, ByVal left As
Integer, ByVal contents As String)
MyBase.New(top, left)
listBoxContents = contents
End Sub
Public Overrides Sub DrawControl()
Console.WriteLine("Writing string to the listbox:
{0}", listBoxContents)
End Sub
Private listBoxContents As String
End Class
105
Public Class Button1
Inherits Control1
Public Sub New(ByVal top As Integer, ByVal left As
Integer)
MyBase.New(top, left)
End Sub
Public Overrides Sub DrawControl()
Console.WriteLine("Drawing a button at {0}, {1}" +
ControlChars.Lf, top, left)
End Sub
End Class
Public Class Tester189
Shared Sub Main()
Dim winArray(3) As Control1
winArray(0) = New Label1(1, 2, "A")
winArray(1) = New Label1(3, 4, "B")
winArray(2) = New Button1(5, 6)
Dim i As Integer
For i = 0 To 2
winArray(i).DrawControl()
Next i
End Sub 'Main
End Class 'Tester
'MustOverride method
Option Strict On
Imports System
Public MustInherit Class Control2
Public Sub New(ByVal top As Integer, ByVal left As
Integer)
Me.top = top
Me.left = left
End Sub
Public MustOverride Sub DrawControl()
106
Protected top As Integer
Protected left As Integer
End Class
Public Class Label2
Inherits Control2
Public Sub New(ByVal top As Integer, ByVal left As
Integer, ByVal contents As String)
MyBase.New(top, left)
listBoxContents = contents
End Sub
Public Overrides Sub DrawControl()
Console.WriteLine("Writing string to the listbox:
{0}", listBoxContents)
End Sub
Private listBoxContents As String
End Class
Public Class Button2
Inherits Control2
Public Sub New(ByVal top As Integer, ByVal left As
Integer)
MyBase.New(top, left)
End Sub
Public Overrides Sub DrawControl()
Console.WriteLine("Drawing a button at {0}, {1}" +
ControlChars.Lf, top, left)
End Sub
End Class
Public Class Tester190
Shared Sub Main()
Dim winArray(3) As Control2
winArray(0) = New Label2(1, 2, "A")
winArray(1) = New Label2(3, 4, "B")
winArray(2) = New Button2(5, 6)
Dim i As Integer
For i = 0 To 2
winArray(i).DrawControl()
Next i
End Sub 'Main
End Class 'Tester
107
'NotOverridable
Public Class Base1
Public Overridable Function greet() As String
Return "Greeting from the Base!"
End Function
End Class
Public Class Derived11
Inherits Base1
Public Overrides Function greet() As String
Return "middle greet"
End Function
End Class
Public Class Derived21
Inherits Derived11
Public NotOverridable Overrides Function greet() As String
'End Function
Return 0
End Function
End Class
Public Class bottom11
Inherits Derived21
End Class
'Overridable Overrides methods
Option Strict On
Imports System
Public Class Control3
Public Sub New(ByVal top As Integer, ByVal left As
Integer)
Me.top = top
Me.left = left
End Sub
Public Overridable Sub DrawControl()
Console.WriteLine("Control: drawing Control at {0},
{1}", top, left)
108
End Sub
Protected top As Integer
Protected left As Integer
End Class
Public Class Label3
Inherits Control3
Public Sub New(ByVal top As Integer, ByVal left As
Integer, ByVal n As String)
MyBase.New(top, left)
text = n
End Sub
Public Overrides Sub DrawControl()
MyBase.DrawControl()
Console.WriteLine("Writing string to the listbox:
{0}", text)
End Sub
Private text As String
End Class
Public Class Button3
Inherits Control3
Public Sub New(ByVal top As Integer, ByVal left As
Integer)
MyBase.New(top, left)
End Sub 'New
Public Overrides Sub DrawControl()
Console.WriteLine("Drawing a button at {0}, {1}" +
ControlChars.Lf, top, Left)
End Sub
End Class
Public Class m192
Shared Sub Main()
Dim win As New Control3(1, 2)
Dim lb As New Label3(3, 4, "test")
Dim b As New Button3(5, 6)
win.DrawControl()
lb.DrawControl()
b.DrawControl()
Dim winArray(3) As Control3
winArray(0) = New Control3(1, 2)
109
winArray(1) = New Label3(3, 4, "AAA")
winArray(2) = New Button3(5, 6)
Dim i As Integer
For i = 0 To 2
winArray(i).DrawControl()
Next i
End Sub
End Class
'Structure
Structure Money1
Private centsAmount As Integer
Public Sub New(ByVal amount As Double)
Me.centsAmount = CInt(amount * 100)
End Sub
End Structure
Module MyModule
Sub Main()
' Dim freebie As Money1
Dim carPrice As Money1 = New Money1(3.95)
End Sub
End Module
'Define and use Structure
Structure CheckRecord
Dim intCheckNumber As Integer
Dim dteCheckDate As Date
Dim sngCheckAmount As Single
Dim strCheckPaidTo As String
110
End Structure
Public Class Test194
Public Shared Sub Main()
Dim udtCheck As CheckRecord
'Add data to the structure.
udtCheck.intCheckNumber = 275
udtCheck.dteCheckDate = #9/12/2001#
udtCheck.sngCheckAmount = 104.25
udtCheck.strCheckPaidTo = "Gas Co."
Console.WriteLine("CHECK INFORMATION")
Console.WriteLine("Number: " &
udtCheck.intCheckNumber)
Console.WriteLine("Date: " & udtCheck.dteCheckDate)
Console.WriteLine("Amount: " &
udtCheck.sngCheckAmount)
Console.WriteLine("Paid To: " &
udtCheck.strCheckPaidTo)
End Sub
End Class
'By value or by reference
Option Strict On
Public Class YourClas
Public Name As String
Public GPA As Double
End Class
Public Structure YourStructure
Public Name As String
Public GPA As Double
End Structure
Public Class Test195
Public Shared Sub Main()
Dim valueByRef As New YourClas()
Dim valueByValue As New YourStructure()
111
valueByRef.Name = "Jill"
valueByRef.GPA = 92.3
valueByValue.Name = "Jill"
valueByValue.GPA = 92.3
Dim ref2 As YourClas = valueByRef
Dim value2 As YourStructure = valueByValue
ref2.GPA += 2
value2.GPA += 2
Console.WriteLine("{0}'s GPA is: {1}",
valueByRef.Name, valueByRef.GPA)
Console.WriteLine("{0}'s GPA is: {1}",
valueByValue.Name, valueByValue.GPA)
End Sub
End Class
'Use Structure as Function parameter
Public Structure CustomerBalance
Dim decBalSavings As Decimal
Dim decBalChecking As Decimal
End Structure
Public Class Test196
Public Shared Sub Main()
Dim udtBalance As CustomerBalance
udtBalance = GetCustomerBalance(1)
Console.WriteLine(udtBalance.decBalChecking)
Console.WriteLine(udtBalance.decBalSavings)
End Sub
Shared Function GetCustomerBalance(ByVal intCustomerID As
Integer) As CustomerBalance
Dim udtBalance As CustomerBalance
udtBalance.decBalChecking = CDec(1000 + 4000 * Rnd())
udtBalance.decBalSavings = CDec(1000 + 15000 * Rnd())
Return udtBalance
112
End Function
End Class
'Class Vs Structure in ByValue and ByRef
Imports System
Public Enum Country
US = 1
CA = 2
End Enum
Public Class AClass
Public Name As String
Public Status As Country
End Class
Public Structure AStruct
Public Name As String
Public Status As Country
End Structure
Public Module Test197
Public Sub ChangeName_Obj_ByVal(ByVal details As AClass,
ByVal NewName As String)
details.Name = NewName
End Sub
Public Sub ChangeName_Obj_ByRef(ByRef details As AClass,
ByVal NewName As String)
details.Name = NewName
End Sub
Public Sub ChangeName_Struct_ByVal(ByVal details As
AStruct, ByVal NewName As String)
details.Name = NewName
End Sub
Public Sub ChangeName_Struct_ByRef(ByRef details As
AStruct, ByVal NewName As String)
details.Name = NewName
End Sub
113
Sub Main()
Dim classInstance As AClass = New AClass()
Dim structInstance As AStruct = New AStruct()
classInstance.Name = "A"
classInstance.Status = Country.CA
structInstance.Name = "B"
structInstance.Status = Country.CA
Console.WriteLine("{0}, {1}", classInstance.Name,
classInstance.Status)
Console.WriteLine("{0}, {1}", structInstance.Name,
structInstance.Status)
Console.WriteLine()
ChangeName_Obj_ByVal(classInstance, "AAAA")
ChangeName_Struct_ByVal(structInstance, "BBBB")
Console.WriteLine("{0},{1}", classInstance.Name,
classInstance.Status)
Console.WriteLine("{0},{1}", structInstance.Name,
structInstance.Status)
Console.WriteLine()
ChangeName_Obj_ByRef(classInstance, "AAAA")
ChangeName_Struct_ByRef(structInstance, "BBBB")
Console.WriteLine("{0}, {1}", classInstance.Name,
classInstance.Status)
Console.WriteLine("{0}, {1}", structInstance.Name,
structInstance.Status)
End Sub
End Module
'Array of Structure
Structure Employee5
Dim strName As String
Dim intSalary As Integer
End Structure
Public Class Test198
Public Shared Sub Main()
Dim aryEmployees(15) As Employee5
Dim intCounter As Integer
114
aryEmployees(0).strName = "J"
aryEmployees(0).intSalary = 3
aryEmployees(1).strName = "B"
aryEmployees(1).intSalary = 6
'Set other array elements here.
aryEmployees(15).strName = "P"
aryEmployees(15).intSalary = 1
'Show the elements of the array.
For intCounter = 0 To 15
Console.WriteLine("Array element: " & intCounter &
vbCrLf & _
"Name: " & aryEmployees(intCounter).strName
& vbCrLf & _
"Salary: " &
aryEmployees(intCounter).intSalary)
Next intCounter
End Sub
End Class
'Try Catch Exception
Option Strict On
Imports System
Class Tester199
Shared Sub Main()
Console.WriteLine("Enter Func2...")
Try
Console.WriteLine("Entering Try block...")
Throw New System.Exception()
Console.WriteLine("Exitintg Try block...")
Catch
Console.WriteLine("Exception caught and handled")
End Try
Console.WriteLine("Exit func2...")
End Sub 'Main
End Class 'Tester
115
'Catch Exception throwed from a Method
Option Strict On
Imports System
Class Tester200
Shared Sub Main()
Console.WriteLine("Enter func1...")
Try
Console.WriteLine("Entering Try block...")
Func1()
Console.WriteLine("Exiting Try block...")
Catch
Console.WriteLine("Exception caught and handled")
End Try
Console.WriteLine("Exit func1...")
End Sub
Public Shared Sub Func1()
Console.WriteLine("Enter Func2...")
Throw New System.Exception()
Console.WriteLine("Exit Func2...")
End Sub
End Class
'Catch different Exception with multiple catch statements
Imports System.IO
Public Class Tester201
Public Shared Sub Main()
Dim y As Integer
Dim x As Integer
Dim z As Integer
116
Try
x = 1
y = 0
z = x / y
Catch e As DivideByZeroException
Console.WriteLine("You have attempted to divide by
zero!")
y = 2
z = x / y
Catch e As OverflowException
Console.WriteLine("You have encountered an
overflow exception. ")
y = 2
z = x / y
Catch e As System.Data.ConstraintException
Console.WriteLine("You have encountered a
constraint exception. ")
y = 2
z = x / y
Finally
Console.WriteLine(x & "/" & y & " = " & z)
End Try
End Sub
End Class
'Catch without Exception type
Public Class Test202
Public Shared Sub Main()
Dim strCaption As String
strCaption = "Answer"
Try
Console.WriteLine(strCaption.Substring(10, 1))
Catch
Console.WriteLine("An error has occurred.")
End Try
End Sub
End Class
117
'Catch custom exception
Public Class MyException
Inherits System.Exception
Sub New(ByVal Message As String)
MyBase.New(Message)
End Sub
End Class
Public Class Tester203
Public Shared Sub Main()
Try
Console.WriteLine("About to generate custom
exception")
Throw (New MyException("** Custom Message **"))
Catch Ex As MyException
Console.WriteLine("Custom Exception thrown " &
Ex.Message)
End Try
End Sub
End Class
'Try Catch with Finally clause
Option Strict On
Imports System
Class Tester204
Public Shared Function DoDivide(ByVal a As Double, ByVal b
As Double) As Double
If b = 0 Then
Throw New System.DivideByZeroException()
End If
If a = 0 Then
118
Throw New System.ArithmeticException()
End If
Return a / b
End Function 'DoDivide
Shared Sub Main()
Try
Console.WriteLine("Open file here")
Dim a As Double = 5
Dim b As Double = 0
Console.WriteLine("{0} / {1} = {2}", a, b,
DoDivide(a, b))
Console.WriteLine("This line may or may not
print")
Catch e As System.DivideByZeroException
Console.WriteLine("DivideByZeroException caught!")
Catch
Console.WriteLine("Unknown exception caught!")
Finally
Console.WriteLine("Close file here.")
End Try
End Sub
End Class
'Finally always executes
Public Class Tester205
Public Shared Sub Main()
DoesNotThrowException()
End Sub
Public Shared Sub DoesNotThrowException()
Try
Console.WriteLine("In DoesNotThrowException")
Catch
Console.WriteLine("This Catch never executes")
Finally
Console.WriteLine("Finally executed in
DoesNotThrowException")
End Try
119
Console.WriteLine("End of DoesNotThrowException")
End Sub ' DoesNotThrowException
End Class
'Finally after multiple catch statements
Module Module206
Sub Main()
Dim intItem1 As Integer = 0
Dim intItem2 As Integer = 128
Dim intResult As Integer
Try
intResult = intItem2 / intItem1
Catch e As OverflowException
Console.WriteLine("An overflow exception
occurred.")
Catch e As OutOfMemoryException
Console.WriteLine("Out of memory.")
Catch e As IndexOutOfRangeException
Console.WriteLine("Array index out of range.")
Finally
Console.WriteLine("Finally")
End Try
End Sub
End Module
' Math.Sqrt and Atan2
Public Class Tester207
Public Shared Sub Main()
Dim magnitude As Single
Dim radians As Single
magnitude = CSng(Math.Sqrt(100 ^ 2 + 120 ^ 2))
radians = CSng(Math.Atan2(100, 123))
120
Console.WriteLine(magnitude)
Console.WriteLine(radians)
End Sub
End Class
'Math. Cos and Sin
Public Class Tester208
Public Shared Sub Main()
Dim X As Single
Dim Y As Single
X = CSng(Math.Cos(100))
Y = CSng(Math.Sin(100))
Console.WriteLine(X)
Console.WriteLine(Y)
End Sub
End Class
'Generating random integers.
Module Tester209
Sub Main()
Dim randomObject As Random = New Random()
Dim randomNumber As Integer
Dim output As String = ""
Dim i As Integer
For i = 1 To 20
randomNumber = randomObject.Next(1, 7)
output &= randomNumber & " "
121
If i Mod 5 = 0 Then ' is i a multiple of 5?
output &= vbCrLf
End If
Next
Console.WriteLine(output)
End Sub
End Module
'Math.Round
Public Class Tester210
Public Shared Sub Main()
Dim digits As Integer
For digits = 0 To 5
Console.WriteLine(Math.Round(Math.PI, digits))
Next digits
End Sub
End Class
'Randomize
Option Strict On
Public Module RandomizeStatement
Public Sub Main()
Dim number As Double = 1.0325
Rnd(-1)
Randomize(number) ' Number is
any Double
For ctr As Integer = 1 To 10
Console.WriteLine(Rnd())
122
Next
End Sub
End Module
'Load Assembly from a url
imports System.Reflection ' necessary for
instantiating assemblies
Imports System.Windows.Forms
Public Class Tester212
Public Shared Sub Main()
Try
Dim strUrl As String = "http" &
"://localhost/MultiFileAssyVB/vbDeploy.exe"
' dim strUrl as String =
"http" & "://localhost/MultiFileAssy/csDeploy.exe"
Dim a As [Assembly] = [Assembly].LoadFrom(strUrl)
Dim t As Type = a.GetType("Form1")
' dim t as Type =
a.GetType("csDeploy.Form1")
Dim o As Object = Activator.CreateInstance(t)
Dim frm As Form = CType(o, Form)
frm.Show()
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
End Sub
End Class
'Get types from Assembly
123
Imports System.Reflection
Module Module214
Sub Main()
Dim thisAssembly As [Assembly] =
[Assembly].GetExecutingAssembly()
Console.Write("Types: ")
Dim TypeObj As Type
For Each TypeObj In thisAssembly.GetTypes()
Console.Write(TypeObj.Name & " ")
Next
End Sub
End Module
'Get Assembly: Code base, Full name, Entry point, Assembly
Cache, Location
Imports System.Reflection
Module Module21
Sub Main()
Dim thisAssembly As [Assembly] =
[Assembly].GetExecutingAssembly()
Console.WriteLine("Code base: " &
thisAssembly.CodeBase)
Console.WriteLine("Full name: " &
thisAssembly.FullName)
Console.WriteLine("Entry point: " &
thisAssembly.EntryPoint.ToString())
Console.WriteLine("From Global Assembly Cache: " &
thisAssembly.GlobalAssemblyCache)
Console.WriteLine("Location: " &
thisAssembly.Location)
End Sub
End Module
'Array declaration
124
Option Strict On
Public Module Arrays
Public Sub Main()
Dim arr As Array
Dim int() As Integer = {12, 16, 20, 24, 28, 32}
arr = CType(int, Array)
Dim byFours() As Integer = {12, 24, 36, 48}
Dim names() As String = {"K", "S", "S", "D", "N"}
Dim miscData() As Object = {"this", 12D, 16UI, "a"c}
Dim objArray() As Object
miscData = names
Dim myArray1a() As Integer ' Uninitialized array
Dim myArray1b As Integer() ' Uninitialized array
Dim myArray2(10) As Integer ' 1-dimensional array with
11 elements
Dim Employees1(,) As Object ' Uninitialized 2-D array
Dim Employees(200, 2) As Object ' 2-D array with 201
and 3 elements
Dim jagged1(9)() As String
Dim jagged2()() As String = New String(9)() {}
Dim myArray1arr As Array
Dim myArray2a As Array =
Array.CreateInstance(GetType(Integer), 10)
Dim members() As Integer = {3, 10}
Dim myArray3a As Array =
Array.CreateInstance(GetType(Integer), members)
End Sub
End Module
'Declaring and allocating an array
Module Tester216
Sub Main()
Dim i As Integer
Dim array As Integer() ' declare array variable
array = New Integer(9) {} ' allocate memory for array
Console.WriteLine("Subscript " & vbTab & "Value")
For i = 0 To array.GetUpperBound(0)
Console.WriteLine(i & vbTab & array(i))
125
Next
Console.WriteLine("The array contains " & _
array.Length & " elements.")
End Sub
End Module
'Initializing arrays
Module Tester217
Sub Main()
Dim i As Integer
Dim array1, array2 As Integer() ' declare two arrays
' initializer list specifies number of elements
' and value of each element
array1 = New Integer() {2, 7, 4, 8, 5, 14, 90, 70, 60,
37}
' allocate array2 based on length of array1
array2 = New Integer(array1.GetUpperBound(0)) {}
' set values in array2 by a calculation
For i = 0 To array2.GetUpperBound(0)
array2(i) = 2 + 2 * i
Next
Console.WriteLine("Subscript " & vbTab & "Array1" &
vbTab & _
"Array2")
' display values for both arrays
For i = 0 To array1.GetUpperBound(0)
Console.WriteLine(i & vbTab & array1(i) & vbTab &
array2(i))
Next
End Sub
End Module
126
'Display the contents of a single-dimension array
Public Class Tester218
Public Shared Sub Main()
Dim sourceArray() As Integer = {1, 2, 3}
Dim result As New System.Text.StringBuilder
Dim counter As Integer
result.Append("{")
For counter = 0 To sourceArray.Length - 1
result.Append(sourceArray(counter).ToString())
If (counter < (sourceArray.Length - 1)) Then
result.Append(",")
Next counter
result.Append("}")
Console.WriteLine(result.ToString())
End Sub
End Class
'Assing array element value by using index
Public Class Test219
Public Shared Sub Main()
Dim arySalaries(15) As Integer
Dim aryNames(15) As String
Dim intCounter As Integer
aryNames(0) = "J"
arySalaries(0) = 34000
aryNames(1) = "B"
arySalaries(1) = 62000
127
'Set other array elements here.
aryNames(15) = "P"
arySalaries(15) = 10300
'Show the elements of the array.
For intCounter = 0 To 15
Console.WriteLine("Array element: " & intCounter &
vbCrLf & _
"Name: " & aryNames(intCounter) & vbCrLf &
_
"Salary: " & arySalaries(intCounter))
Next intCounter
End Sub
End Class
'Computing sum of elements in array.
Module Tester220
Sub Main()
Dim array As Integer() = New Integer() _
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim total As Integer = 0, i As Integer
For i = 0 To array.GetUpperBound(0)
total = total + array(i)
Next
Console.WriteLine("Total of array elements: " & total)
End Sub
End Module
128
'Initialize Array element during declaration
Option Strict On
Imports System
Public Class Employee23
Private empID As Integer
Public Sub New(ByVal empID As Integer)
Me.empID = empID
End Sub
Public Overrides Function ToString() As String
Return empID.ToString()
End Function
End Class
Class Tester227
Public Shared Sub Main()
Dim intArray As Integer() = {2, 4, 6, 8, 10}
Dim empArray As Employee23() = _
{New Employee23(5), New Employee23(7), New
Employee23(9)}
Console.WriteLine("The Integer array...")
Dim theInt As Integer
For Each theInt In intArray
Console.WriteLine(theInt.ToString())
Next theInt
Console.WriteLine("The employee array...")
Dim e As Employee23
For Each e In empArray
Console.WriteLine(e.ToString())
Next e
End Sub 'Run
End Class
'Array Resize
129
Public Class Tester222
Public Shared Sub Main()
Dim result As New System.Text.StringBuilder
Dim arrayInsert() As String = {"O", "A", "G", "B",
"B"}
' ----- Show the contents before insertion.
result.AppendLine("Before insertion:")
For Each fruit As String In arrayInsert
result.AppendLine(fruit)
Next fruit
' ----- Insert more fruit.
InsertArrayElement(Of String)(arrayInsert, 2,
"Lemons")
' ----- Show the contents after insertion.
result.AppendLine()
result.AppendLine("After insertion:")
For Each fruit As String In arrayInsert
result.AppendLine(fruit)
Next fruit
Console.WriteLine(result.ToString())
End Sub
Public Shared Sub InsertArrayElement(Of T)( _
ByRef sourceArray() As T, _
ByVal insertIndex As Integer, _
ByVal newValue As T)
Dim newPosition As Integer
Dim counter As Integer
newPosition = insertIndex
If (newPosition < 0) Then newPosition = 0
If (newPosition > sourceArray.Length) Then _
newPosition = sourceArray.Length
Array.Resize(sourceArray, sourceArray.Length + 1)
For counter = sourceArray.Length - 2 To newPosition
Step -1
sourceArray(counter + 1) = sourceArray(counter)
Next counter
sourceArray(newPosition) = newValue
End Sub
End Class
130
'Insert element in the middle of an Array
Public Class Tester223
Public Shared Sub Main()
Dim result As New System.Text.StringBuilder
Dim arrayInsert() As String = {"O", "A", "G", "B",
"B"}
' ----- Show the contents before insertion.
'result.AppendLine("Before insertion:")
Console.WriteLine("Before insertion")
For Each fruit As String In arrayInsert
result.AppendLine(fruit)
Next fruit
' ----- Insert more fruit.
InsertArrayElement(Of String)(arrayInsert, 2,
"Lemons")
' ----- Show the contents after insertion.
result.AppendLine()
result.AppendLine("After insertion:")
For Each fruit As String In arrayInsert
result.AppendLine(fruit)
Next fruit
Console.WriteLine(result.ToString())
End Sub
Public Shared Sub InsertArrayElement(Of T)( _
ByRef sourceArray() As T, _
ByVal insertIndex As Integer, _
ByVal newValue As T)
Dim newPosition As Integer
Dim counter As Integer
newPosition = insertIndex
If (newPosition < 0) Then newPosition = 0
If (newPosition > sourceArray.Length) Then _
newPosition = sourceArray.Length
Array.Resize(sourceArray, sourceArray.Length + 1)
For counter = sourceArray.Length - 2 To newPosition
Step -1
sourceArray(counter + 1) = sourceArray(counter)
Next counter
131
sourceArray(newPosition) = newValue
End Sub
End Class
'One dimesional array performance
Public Class Test224
Public Shared Sub Main()
Dim start_time As DateTime
Dim stop_time As DateTime
Dim elapsed_time As TimeSpan
Dim num_items As Integer = 10000
Dim array1(0 To num_items - 1) As Integer
start_time = Now
For i As Integer = 0 To num_items - 1
array1(i) = i
Next i
stop_time = Now
elapsed_time = stop_time.Subtract(start_time)
Console.WriteLine(elapsed_time.TotalSeconds())
Erase array1
End Sub
End Class
'Two dimesional array performance
Public Class Test225
Public Shared Sub Main()
Dim start_time As DateTime
Dim stop_time As DateTime
132
Dim elapsed_time As TimeSpan
Dim num_items As Integer = 10000
' Two-dimensional array.
Dim array2(0 To 0, 0 To num_items - 1) As Integer
start_time = Now
For i As Integer = 0 To num_items - 1
array2(0, i) = i
Next i
stop_time = Now
elapsed_time = stop_time.Subtract(start_time)
Console.WriteLine(elapsed_time.TotalSeconds())
Erase array2
End Sub
End Class
'Array Clone
Public Class Tester12
Public Shared Sub Main()
Dim arrayA() As String = {"One", "Two", "Three",
"Four", "Five", "Six"}
Console.WriteLine(Join(arrayA, ","))
Dim arrayB() As String = {"A", "B", "C", "D", "E",
"E", "F", "G", "H"}
Console.WriteLine(Join(arrayB, ","))
' ----- Make a reference copy.
Dim arrayC() As String = arrayA
Console.WriteLine(Join(arrayC, ","))
' ----- Make a full, unique copy of all elements.
Dim arrayD() As String = arrayA.Clone
Console.WriteLine(Join(arrayD, ","))
End Sub
End Class
133
'Array length: negative
Option Strict On
Public Module ValidArray
Public Sub Main()
Dim emptyArray(-1) As String
For Each element As String In emptyArray
Console.WriteLine(element)
Next
End Sub
End Module
'Reorder the elements of an array in a random order
Public Class Tester228
Public Shared Sub Main()
Dim arrayShuffle() As String = {"A", "B", "C", "D",
"E"}
For Each fruit As String In arrayShuffle
Console.WriteLine(fruit)
Next fruit
Shuffle(arrayShuffle)
For Each fruit As String In arrayShuffle
Console.WriteLine(fruit)
Next fruit
End Sub
Public Shared Sub Shuffle(ByRef shuffleArray() As Object)
Dim counter As Integer
Dim newPosition As Integer
Dim shuffleMethod As New Random
134
Dim tempObject As Object
For counter = 0 To shuffleArray.Length - 1
newPosition = shuffleMethod.Next(0,
shuffleArray.Length - 1)
tempObject = shuffleArray(counter)
shuffleArray(counter) = shuffleArray(newPosition)
shuffleArray(newPosition) = tempObject
Next counter
End Sub
End Class
'Swap elements in an array
Public Class Tester229
Public Shared Sub Main()
Dim result As New System.Text.StringBuilder
Dim arraySwap() As String = {"A", "B", "C", "D", "E"}
Swap(arraySwap, 1, 3)
For Each fruit As String In arraySwap
Console.WriteLine(fruit)
Next fruit
End Sub
Public Shared Sub Swap(ByRef swapArray() As Object, _
ByVal first As Integer, ByVal second As Integer)
Dim tempObject As Object
tempObject = swapArray(first)
swapArray(first) = swapArray(second)
swapArray(second) = tempObject
End Sub
End Class
'Use For loop to initialize Integer array
135
Module Module230
Sub Main()
Dim Students(50) As Integer
Dim I As Integer
For I = 0 To 50
Students(I) = I
Next
For I = 0 To 50
Console.WriteLine(Students(I))
Next
End Sub
End Module
'Show and use the array boundaries
Public Class Test231
Public Shared Sub Main()
Dim aryNames(9) As String
Dim intCounter As Integer
'Show the array boundaries.
Console.WriteLine("LOWER BOUND: " &
aryNames.GetLowerBound(0))
Console.WriteLine("UPPER BOUND: " &
aryNames.GetUpperBound(0))
Console.WriteLine("LENGTH: " & aryNames.Length)
'Populate the array.
For intCounter = 0 To aryNames.GetUpperBound(0)
aryNames(intCounter) = "Element position = " &
intCounter
Next intCounter
'Show the elements of the array.
For intCounter = 0 To aryNames.GetUpperBound(0)
Console.WriteLine("Element position = " &
intCounter)
136
Next intCounter
End Sub
End Class
'Use array UBound in For loop
Module Module232
Sub Main()
Dim Scores(2) As Integer
Scores(0) = 45
Scores(1) = 55
Scores(2) = 65
For intLoopIndex As Integer = 0 To UBound(Scores)
Console.WriteLine("Score(" & intLoopIndex & ") = "
& Scores(intLoopIndex))
Next intLoopIndex
End Sub
End Module
'GetUpperBound
Module Tester233
Sub Main()
Dim answer, rating As Integer
Dim output As String
Dim responses As Integer()
responses = New Integer() {1, 2, 6, 4, 8, 5, 9, 7, _
8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, _
8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10}
' response frequency array (indices 0 through 10)
Dim frequency As Integer() = New Integer(10) {}
137
' count frequencies
For answer = 0 To responses.GetUpperBound(0)
frequency(responses(answer)) += 1
Next
Console.WriteLine("Rating " & vbTab & "Frequency ")
For rating = 1 To frequency.GetUpperBound(0)
Console.WriteLine(rating & vbTab &
frequency(rating))
Next
End Sub ' Main
End Module
'Array lower bound and upper bound
Option Strict On
Public Class CArray
Public Shared Sub Main()
Dim dims() As Integer = {10} ' Number of elements in
array
Dim bnds() As Integer = {50} ' Lower bound of array
Dim Scores As Array =
Array.CreateInstance(GetType(Integer), dims, bnds)
Console.WriteLine(UBound(Scores))
Console.WriteLine(LBound(Scores))
End Sub
End Class
'Get array lower bound, upper bound and length
Module Tester235
Sub Main()
Dim Values() As Integer = {100, 200, 300, 400, 500}
Dim MyValues(5) As Integer
Dim Prices() As Double = {25.5, 4.95, 33.4}
138
Dim I As Integer
For I = 0 To 4
Console.Write(Values(I) & " ")
Next
Console.WriteLine()
Console.WriteLine("Array length: " & Values.Length)
Console.WriteLine("Array lowerbound: " &
Values.GetLowerBound(0))
Console.WriteLine("Array upperbound: " &
Values.GetUpperBound(0))
End Sub
End Module
'Pass array
Imports System
Imports Microsoft.VisualBasic
Module Test236
Dim i As Integer
Public Sub AddOne(ByVal InputArray() As Integer)
For i = 0 To 3
InputArray(i) = InputArray(i) + 1
Next
End Sub
Public Sub AddTwo(ByVal InputArray() As Integer)
Dim tempArray() As Integer
tempArray = InputArray.Clone
For i = 0 To 3
tempArray(i) = tempArray(i) + 2
Next
End Sub
Sub Main()
Dim intArray() As Integer = {6, 8, 7, 6}
For i = 0 To 3
Console.WriteLine("{0}", intArray(i))
139
Next
AddOne(intArray)
For i = 0 To 3
Console.WriteLine("{0}", intArray(i))
Next
AddTwo(intArray)
For i = 0 To 3
Console.WriteLine("{0}", intArray(i))
Next
End Sub
End Module
'Testing the effects of passing array references using ByVal
and ByRef
Module Tester237
Sub Main()
Dim i As Integer
Dim firstArray As Integer()
Dim firstArrayCopy As Integer()
firstArray = New Integer() {1, 2, 3}
firstArrayCopy = firstArray
For i = 0 To firstArray.GetUpperBound(0)
Console.Write(firstArray(i) & " ")
Next
FirstDouble(firstArray)
For i = 0 To firstArray.GetUpperBound(0)
Console.Write(firstArray(i) & " ")
Next
If firstArray Is firstArrayCopy Then
Console.WriteLine("The references are equal.")
Else
Console.WriteLine("The references are not equal.")
End If
Dim secondArray As Integer()
Dim secondArrayCopy As Integer()
secondArray = New Integer() {1, 2, 3}
secondArrayCopy = secondArray
140
For i = 0 To secondArray.GetUpperBound(0)
Console.Write(secondArray(i) & " ")
Next
SecondDouble(secondArray)
For i = 0 To secondArray.GetUpperBound(0)
Console.Write(secondArray(i) & " ")
Next
If secondArray Is secondArrayCopy Then
Console.WriteLine("The references are equal.")
Else
Console.WriteLine("The references are not equal.")
End If
End Sub ' Main
Sub FirstDouble(ByVal array As Integer())
Dim i As Integer
For i = 0 To array.GetUpperBound(0)
array(i) *= 2
Next
array = New Integer() {11, 12, 13}
End Sub
Sub SecondDouble(ByRef array As Integer())
Dim i As Integer
For i = 0 To array.GetUpperBound(0)
array(i) *= 2
Next
array = New Integer() {11, 12, 13}
End Sub
End Module
'Array.GetLength, Array.GetUpperBound
Public Class Test238
Public Shared Sub Main()
Dim aryStatistics(14) As Integer
Console.WriteLine("RANK: " & aryStatistics.Rank)
141
'Dimensions in array.
Console.WriteLine("TOTAL ELEMENTS: " &
aryStatistics.Length) 'Total elements in array.
Console.WriteLine("ELEMENTS IN FIRST: " &
aryStatistics.GetLength(0)) 'Elements in first dimension.
Console.WriteLine("ELEMENTS IN SECOND: " &
aryStatistics.GetLength(1)) 'Elements in second dimension.
Console.WriteLine("LAST INDEX IN FIRST: " &
aryStatistics.GetUpperBound(0)) 'Last index in the first
dimension.
Console.WriteLine("LAST INDEX IN SECOND: " &
aryStatistics.GetUpperBound(1)) 'Last index in the second
dimension.
End Sub
End Class
'Array.IndexOf
Public Class Test239
Public Shared Sub Main()
Dim values() As Integer = {10, 20, 30, 40, 50, 60, 40}
'For i As Integer = 0 To 10
' values(i) = i
'Next i
Console.WriteLine(Array.IndexOf(values, 40).ToString)
Console.WriteLine(Array.LastIndexOf(values,
40).ToString)
End Sub
End Class
'Array.LastIndexOf
Public Class Test240
Public Shared Sub Main()
142
Dim values(10) As Integer
For i As Integer = 0 To 10
values(i) = i
Next i
Console.WriteLine(Array.LastIndexOf(values,
3).ToString)
End Sub
End Class
'Reverse array elements
Module Tester241
Sub Main()
Dim Values() As Integer = {100, 200, 300, 400, 500}
'Dim MyValues(5) As Integer
'Dim Prices() As Double = {25.5, 4.95, 33.4}
Dim I As Integer
For I = 0 To 4
Console.Write(Values(I) & " ")
Next
Console.WriteLine()
Array.Reverse(Values)
For I = 0 To 4
Console.Write(Values(I) & " ")
Next
Console.WriteLine()
Array.Sort(Values)
For I = 0 To 4
Console.Write(Values(I) & " ")
Next
End Sub
End Module
'Use Array.Sort() to sort object array
143
Imports System
Module MyModule242
Sub Main()
Dim salaries(4) As Salary
salaries(0) = New Salary(9)
salaries(1) = New Salary(4)
salaries(2) = New Salary(8)
salaries(3) = salaries(2)
salaries(4) = New Salary(6)
Console.WriteLine("Unsorted array:")
Dim salary As Salary
For Each salary In salaries
Console.WriteLine("{0}", salary)
Next
Array.Sort(salaries)
Console.WriteLine(vbCrLf & "Sorted array:")
For Each salary In salaries
Console.WriteLine("{0}", salary)
Next
End Sub
End Module
Structure Salary
Implements IComparable
Private value As Integer
Public Sub New(ByVal amount As Double)
Me.value = CInt(amount * 100)
End Sub
Public Function CompareTo(ByVal other As Object) As
Integer Implements IComparable.CompareTo
Dim m2 As Salary = CType(other, Salary)
If Me.value < m2.value Then
Return -1
ElseIf Me.value = m2.value Then
Return 0
Else
Return +1
End If
End Function
Public Overrides Function ToString() As String
Return Me.value
144
End Function
End Structure
'Copy array elements from one array to another
Module Tester243
Sub Main()
Dim Values() As Integer = {100, 200, 300, 400, 500}
Dim MyValues(5) As Integer
'Dim Prices() As Double = {25.5, 4.95, 33.4}
Dim I As Integer
For I = 0 To 4
Console.Write(Values(I) & " ")
Next
Console.WriteLine()
' Copy one array to another
Values.CopyTo(MyValues, 0)
For I = 0 To 4
Console.Write(MyValues(I) & " ")
Next
End Sub
End Module
'Array.Copy: Copy elements by position
Public Class Tester244
Public Shared Sub Main()
Dim arrayA() As String = {"One", "Two", "Three",
"Four", "Five", "Six"}
Console.WriteLine(Join(arrayA, ","))
Dim arrayB() As String = {"A", "B", "C", "D", "E",
"E", "F", "G", "H"}
Console.WriteLine(Join(arrayB, ","))
' ----- Make a reference copy.
Dim arrayC() As String = arrayA
Console.WriteLine(Join(arrayC, ","))
' ----- Copy elements by position.
Array.Copy(arrayB, 0, arrayA, 1, 3)
Console.WriteLine(Join(arrayA, ","))
145
End Sub
End Class
'Array SetValue and GetValue
Imports System.Collections.Generic
Public Class Test245
Public Shared Sub Main()
Dim squares As Array =
Array.CreateInstance(GetType(Integer), 11)
For i As Integer = 0 To 10
squares.SetValue(i * i, i)
Next i
For i As Integer = 0 To 10
Console.WriteLine(squares.GetValue(i).ToString)
Next i
End Sub
End Class
'Populate Object array
Option Strict On
Imports System
Public Class Employee246
Private empID As Integer
Public Sub New(ByVal empID As Integer)
Me.empID = empID
End Sub
End Class
Class Tester246
Shared Sub Main()
Dim intArray As Integer()
146
Dim empArray As Employee246()
intArray = New Integer(5) {}
empArray = New Employee246(3) {}
Dim i As Integer
For i = 0 To empArray.Length - 1
empArray(i) = New Employee246(i + 5)
i = i + 1
Next
End Sub
End Class
'Reverse the contents of an array
Public Class Tester247
Public Shared Sub Main()
Dim arrayReverse() As String = {"A", "B", "C", "D",
"E"}
For Each fruit As String In arrayReverse
Console.WriteLine(fruit)
Next fruit
Array.Reverse(arrayReverse)
For Each fruit As String In arrayReverse
Console.WriteLine(fruit)
Next fruit
End Sub
End Class
'Array Reverse and Sort
Option Strict On
Imports System
Class Tester248
Public Shared Sub DisplayArray(ByVal theArray() As Object)
Dim obj As Object
147
For Each obj In theArray
Console.WriteLine("Value: {0}", obj)
Next obj
Console.WriteLine(ControlChars.Lf)
End Sub
Public Shared Sub Main()
Dim myArray As [String]() = {"W", "s", "J", "t"}
Console.WriteLine("Display myArray...")
DisplayArray(myArray)
Console.WriteLine("Reverse and display myArray...")
Array.Reverse(myArray)
DisplayArray(myArray)
Dim myOtherArray As [String]() = {"W", "d", "e", "s",
"o", "e", "f", "t"}
Console.WriteLine("Display myOtherArray...")
DisplayArray(myOtherArray)
Console.WriteLine("Sort and display myOtherArray...")
Array.Sort(myOtherArray)
DisplayArray(myOtherArray)
End Sub 'Main
End Class 'Tester
'Array.BinarySearch
Imports System.Collections
Public Class Tester249
Shared Sub Main()
Dim integerValues As Integer() = {1, 2, 3, 4, 5, 6}
Dim integerElement As Integer
For Each integerElement In integerValues
Console.WriteLine(integerElement)
Next
Dim result As Integer =
Array.BinarySearch(integerValues, 5)
If result >= 0 Then
Console.WriteLine("5 found at element " & result &
" in integerValues")
Else
Console.WriteLine("5 not found" & " in
148
integerValues")
End If
End Sub
End Class
'Array.Sort and Array.IndexOf
Imports System.Collections
Public Class Test250
Public Shared Sub Main()
Dim StringArray() As String = {"This", "is", "a",
"test"}
Dim E As IEnumerator = StringArray.GetEnumerator()
While (E.MoveNext())
Console.WriteLine(E.Current())
End While
Dim NewArray(StringArray.Length) As String
Array.Copy(StringArray, NewArray, StringArray.Length)
Console.WriteLine(Array.IndexOf(NewArray, "a"))
End Sub
End Class
'Linear search of an array
Public Class Tester256
Public Shared Sub Main()
Dim array1 As Integer() = New Integer(19) {}
Dim randomNumber As Random = New Random()
Dim i As Integer
' creates string containing 11 random numbers
149
For i = 0 To array1.GetUpperBound(0)
array1(i) = randomNumber.Next(1000)
Console.Write(array1(i) & " ")
Next
Console.WriteLine("")
Dim searchKey As Integer = 12
Dim element As Integer = LinearSearch(searchKey,
array1)
If element <> -1 Then
Console.WriteLine("Found Value in index " &
element)
Else
Console.WriteLine("Value Not Found")
End If
End Sub
Shared Function LinearSearch(ByVal key As Integer, _
ByVal numbers As Integer()) As Integer
Dim n As Integer
' structure iterates linearly through array
For n = 0 To numbers.GetUpperBound(0)
If numbers(n) = key Then
Return n
End If
Next
Return -1
End Function ' LinearSearch
End Class
'Demonstrating binary search of an array
Public Class Tester253
Shared array1 As Integer() = New Integer(14) {}
Public Shared Sub Main()
150
Dim i As Integer
For i = 0 To array1.GetUpperBound(0)
array1(i) = 2 * i
Next
Dim searchKey As Integer = 8
Dim element As Integer = BinarySearch(array1,
searchKey)
If element <> -1 Then
Console.WriteLine("Found value in element " &
element)
Else
Console.WriteLine("Value not found")
End If
End Sub
' performs binary search
Shared Function BinarySearch(ByVal array As Integer(), _
ByVal key As Integer) As Integer
Dim low As Integer = 0 ' low index
Dim high As Integer = array.GetUpperBound(0) ' high
index
Dim middle As Integer ' middle index
While low <= high
middle = (low + high) \ 2
If key = array(middle) Then ' match
Return middle
ElseIf key < array(middle) Then ' search low end
high = middle - 1 ' of array
Else
low = middle + 1
End If
End While
Return -1 ' search key not found
End Function ' BinarySearch
End Class
'Initializing multi-dimensional arrays
151
Module Tester254
Sub Main()
Dim i, j As Integer
' create rectangular two-dimensional array
Dim array1 As Integer(,)
array1 = New Integer(,) {{1, 2, 3}, {4, 5, 6}}
' create jagged two-dimensional array
Dim array2 As Integer()() = New Integer(2)() {}
array2(0) = New Integer() {1, 2}
array2(1) = New Integer() {3}
array2(2) = New Integer() {4, 5, 6}
For i = 0 To array1.GetUpperBound(0)
For j = 0 To array1.GetUpperBound(1)
Console.Write(array1(i, j) & " ")
Next
Console.WriteLine("")
Next
For i = 0 To array2.GetUpperBound(0)
For j = 0 To array2(i).GetUpperBound(0)
Console.WriteLine(array2(i)(j) & " ")
Next
Console.WriteLine("")
Next
End Sub
End Module
'Rectangular Array
Option Strict On
Imports System
Class Tester255
Shared Sub Main()
152
Const rowsUB As Integer = 4
Const columnsUB As Integer = 3
Dim rectangularArray(rowsUB, columnsUB) As Integer
Dim i As Integer
For i = 0 To rowsUB - 1
Dim j As Integer
For j = 0 To columnsUB - 1
rectangularArray(i, j) = i + j
Next j
Next i
For i = 0 To rowsUB - 1
Dim j As Integer
For j = 0 To columnsUB - 1
Console.WriteLine( _
"rectangularArray[{0},{1}] = {2}", _
i, j, rectangularArray(i, j))
Next j
Next i
End Sub
End Class
'Define and initialize the two dimensional array
Imports System
Class Tester25
Public Shared Sub Main()
Const rowsUB As Integer = 4
Const columnsUB As Integer = 3
Dim rectangularArray As Integer(,) = _
{{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}}
Dim i As Integer
For i = 0 To rowsUB - 1
Dim j As Integer
For j = 0 To columnsUB - 1
Console.WriteLine( _
"rectangularArray[{0},{1}] = {2}", _
i, j, rectangularArray(i, j))
Next j
Next i
End Sub 'Run
153
End Class
'Jagged two-dimensional array example.
Module Tester257
Dim lastStudent, lastExam As Integer
Sub Main()
Dim i As Integer
' jagged array with 3 rows of exam scores
Dim gradeArray()() As Integer
gradeArray(0) = New Integer() {7, 8, 6, 3}
gradeArray(1) = New Integer() {8, 7, 9, 1}
gradeArray(2) = New Integer() {0, 0, 6, 1}
' upper bounds for array manipulations
lastStudent = gradeArray.GetUpperBound(0)
lastExam = gradeArray(0).GetUpperBound(0)
Console.WriteLine("Lowest grade: " & _
Minimum(gradeArray) & vbCrLf & "Highest grade: " &
_
Maximum(gradeArray))
For i = 0 To lastStudent
Console.WriteLine("Average for student " & _
i & " is " & Average(gradeArray(i)))
Next
End Sub ' Main
Function Minimum(ByVal grades As Integer()()) _
As Integer
Dim lowGrade As Integer = 100
Dim i, j As Integer
For i = 0 To lastStudent
For j = 0 To lastExam
If grades(i)(j) < lowGrade Then
lowGrade = grades(i)(j)
End If
Next
154
Next
Return lowGrade
End Function ' Minimum
Function Maximum(ByVal grades As Integer()()) _
As Integer
Dim highGrade As Integer = 0
Dim i, j As Integer
For i = 0 To lastStudent
For j = 0 To lastExam
If grades(i)(j) > highGrade Then
highGrade = grades(i)(j)
End If
Next
Next
Return highGrade
End Function ' Maximum
Function Average(ByVal setOfGrades As Integer()) _
As Double
Dim i As Integer, total As Integer = 0
For i = 0 To lastExam
total += setOfGrades(i)
Next
Return total / setOfGrades.Length
End Function ' Average
End Module
'Declare the jagged array as 4 rows high
Option Strict On
Imports System
Public Class jaggedarray
Public Shared Sub Main()
Const rowsUB As Integer = 3 ' upper bounds
Const rowZero As Integer = 5
Const rowOne As Integer = 2
Const rowTwo As Integer = 3
Const rowThree As Integer = 5
Dim i As Integer
155
Dim jaggedArray(rowsUB)() As Integer
ReDim jaggedArray(0)(rowZero)
ReDim jaggedArray(1)(rowOne)
ReDim jaggedArray(2)(rowTwo)
ReDim jaggedArray(3)(rowThree)
jaggedArray(0)(3) = 15
jaggedArray(1)(1) = 12
jaggedArray(2)(1) = 9
jaggedArray(2)(2) = 99
jaggedArray(3)(0) = 10
jaggedArray(3)(1) = 11
jaggedArray(3)(2) = 12
jaggedArray(3)(3) = 13
jaggedArray(3)(4) = 14
For i = 0 To rowZero
Console.WriteLine("jaggedArray(0)({0}) = {1}", _
i, jaggedArray(0)(i))
Next
For i = 0 To rowOne
Console.WriteLine("jaggedArray(1)({0}) = {1}", _
i, jaggedArray(1)(i))
Next
For i = 0 To rowTwo
Console.WriteLine("jaggedArray(2)({0}) = {1}", _
i, jaggedArray(2)(i))
Next
For i = 0 To rowThree
Console.WriteLine("jaggedArray(3)({0}) = {1}", _
i, jaggedArray(3)(i))
Next
End Sub
End Class
'Reference elements in two dimensional array
Public Class Test259
Public Shared Sub Main()
Dim aryBoard(9, 9) As Integer
156
'Move the element.
aryBoard(0, 0) = 0
aryBoard(2, 4) = 1
'Check for the element.
If aryBoard(0, 0) = 1 Then
Console.WriteLine("The piece was found.")
Else
Console.WriteLine("The piece was not found.")
End If
End Sub
End Class
'Use For Each/Next to find an element in a two dimension array
Module modForEach
Sub Main()
Dim gradeArray As Integer(,) = New Integer(,) _
{{77, 68, 86, 73}, {98, 87, 89, 81}, {70, 90, 86,
81}}
Dim grade As Integer
Dim lowGrade As Integer = 100
For Each grade In gradeArray
If grade < lowGrade Then
lowGrade = grade
End If
Next
Console.WriteLine("The minimum grade is: {0}",
lowGrade)
End Sub ' Main
End Module
'Set the array of arrays
157
Public Class Test261
Public Shared Sub Main()
Dim aryIntArray(9) As Integer
Dim aryStrArray(99) As String
Dim aryBigArray(1) As Object
Dim intCounter As Integer
'Populate array aryIntArray.
For intCounter = 0 To 9
aryIntArray(intCounter) = intCounter
Next
'Populate array aryStrArray.
For intCounter = 0 To 99
aryStrArray(intCounter) = "ITEM: " &
intCounter.ToString("0000")
Next
'Set the array of arrays.
aryBigArray(0) = aryIntArray
aryBigArray(1) = aryStrArray
'Display some array values.
Console.WriteLine(aryBigArray(0)(7))
Console.WriteLine(aryBigArray(1)(16))
End Sub
End Class
'ReDim an array
Module Module262
Sub Main()
Dim Scores() As Integer
ReDim Scores(1)
Scores(0) = 25
Scores(1) = 75
ReDim Preserve Scores(5)
Scores(2) = 95
Scores(3) = 35
Scores(4) = 65
Scores(5) = 85
Console.WriteLine("Scores(3) = " & Scores(3))
158
End Sub
End Module
'Redim Preserve array
Option Strict On
Public Module modMain263
Public Sub Main()
Dim PowerOf2() As Integer = {0, 1, 2, 4, 8, 16, 32,
64, 128, 256, 512, 1024}
ReDim Preserve PowerOf2(PowerOf2.GetUpperBound(0) \ 2)
For Each int As Integer In PowerOf2
Console.Write("--{0}--", int)
Next
End Sub
End Module
'ReDim string array length
Public Class Tester264
Public Shared Sub Main()
Dim DaysOfTheWeek() As String
ReDim DaysOfTheWeek(7)
DaysOfTheWeek(0) = "Monday"
DaysOfTheWeek(1) = "Tuesday"
DaysOfTheWeek(2) = "Wednesday"
DaysOfTheWeek(3) = "Thursday"
DaysOfTheWeek(4) = "Friday"
DaysOfTheWeek(5) = "Saturday"
DaysOfTheWeek(6) = "Sunday"
Console.WriteLine(DaysOfTheWeek(1))
159
End Sub
End Class
'Dynamic array
Option Strict On
Public Class DynamicArray
Public Shared Sub Main()
Dim index As Integer = 10
Dim arr(index) As Integer
arr(index) = CInt(index ^ 2)
index = 20
ReDim Preserve arr(index)
arr(index) = CInt(index ^ 2)
index = 10
ReDim Preserve arr(index)
Console.WriteLine(arr(index))
End Sub
End Class
'Dimension the array at runtime
Public Class Test266
Public Shared Sub Main()
Dim aryDynArray() As Integer
Dim intResult As Integer
Dim intCounter As Integer
'Dimension the array at runtime.
intResult = 12
ReDim aryDynArray(intResult - 1)
Console.WriteLine("Array size is: " &
aryDynArray.Length)
'Populate the array.
160
For intCounter = 0 To aryDynArray.GetUpperBound(0)
aryDynArray(intCounter) = intCounter + 100
Next intCounter
End Sub
End Class
'Redimension the array and preserve its element values
Public Class Test297
Public Shared Sub Main()
Dim aryDynArray() As Integer
Dim intResult As Integer
Dim intCounter As Integer
'Dimension the array at runtime.
intResult = 12
ReDim aryDynArray(intResult - 1)
Console.WriteLine("Array size is: " &
aryDynArray.Length)
'Populate the array.
For intCounter = 0 To aryDynArray.GetUpperBound(0)
aryDynArray(intCounter) = intCounter + 100
Next intCounter
'Redimension the array and preserve its element
values.
ReDim Preserve
aryDynArray(aryDynArray.GetUpperBound(0) + 1)
Console.WriteLine("Array size is: " &
aryDynArray.Length)
Console.WriteLine("First array value is: " &
aryDynArray(0))
'Erase the array.
Erase aryDynArray
End Sub
End Class
161
'Use ReDim Preserve to add elements to an array
Public Class Tester268
Public Shared Sub Main()
Dim growingArray() As String = Nothing
' ----- Add elements to the array.
For counter As Integer = 0 To 2
ReDim Preserve growingArray(counter)
growingArray(counter) = (counter + 1).ToString
Next counter
' ----- Display the results.
For Each workText As String In growingArray
Console.WriteLine(workText)
Next workText
End Sub
End Class
'Inserting items into a collection by index
Public Class Tester269
Public Shared Sub Main()
Dim wordCollection As New Collection
wordCollection.Add("This")
wordCollection.Add("is")
wordCollection.Add("a")
wordCollection.Add("collection")
wordCollection.Add("of")
wordCollection.Add("words")
' ----- Insert a word after item 3.
wordCollection.Add("slightly", , , 3)
' ----- Insert a word before item 5.
wordCollection.Add("longer", , 5)
For Each word As String In wordCollection
Console.WriteLine(word)
Next word
162
End Sub
End Class
' Add key value pair to Collection
Option Strict On
Imports System.Collections
Public Class Collect
Public Shared Sub Main()
Dim sta As New Collection
sta.Add("New York", "NY")
sta.Add("Michigan", "MI")
sta.Add("New Jersey", "NJ")
sta.Add("Massachusetts", "MA")
For Each stcode As String In sta
Console.WriteLine(stcode)
Next
End Sub
End Class
'Store objects in Collection and retrieve by key and index
Imports System
Public Class Employee271
Private myEmpID As Integer
Public Sub New(ByVal empID As Integer)
Me.myEmpID = empID
End Sub 'New
Public Overrides Function ToString() As String
Return myEmpID.ToString()
End Function 'ToString
Public Property EmpID() As Integer
Get
Return myEmpID
End Get
163
Set(ByVal Value As Integer)
myEmpID = Value
End Set
End Property
End Class 'Employee
Class Tester271
Shared Sub Main()
Dim intCollection As New Collection()
Dim empCollection As New Collection()
Dim empCollection2 As New Collection()
Dim i As Integer
For i = 0 To 4
empCollection.Add(New Employee271(i + 100))
intCollection.Add((i * 5))
Next i
empCollection2.Add(New Employee271(1), "G")
empCollection2.Add(New Employee271(2), "J")
empCollection2.Add(New Employee271(3), "T")
For Each i In intCollection
Console.Write("{0} ", i.ToString())
Next i
Console.WriteLine()
Console.WriteLine("Employee collection...")
Dim e As Employee
For Each e In empCollection
Console.Write("{0} ", e.ToString())
Next e
Console.WriteLine()
Console.WriteLine("Employee collection 2...")
For Each e In empCollection2
Console.Write("{0} ", e.ToString())
Next e
Console.WriteLine()
Dim emp As Employee
emp = empCollection2.Item("J")
Console.WriteLine(emp.ToString())
emp = empCollection2.Item(1)
Console.WriteLine("Index(1) retrieved empID {0}",
emp.ToString())
End Sub
End Class
164
'Get Enumerator from Collection
Imports System.Collections
Public Class Enumerate
Public Shared Sub Main()
Dim weights As New Collection
Dim iterator As IEnumerator
weights.Add("ounces", "oz")
weights.Add("pounds", "lbs")
weights.Add("kilograms", "kg")
weights.Add("milligrams", "mg")
iterator = weights.GetEnumerator
Do While iterator.MoveNext
Console.WriteLine(iterator.Current)
Loop
End Sub
End Class
'Deleting the members of a collection
Option Strict On
Public Module CollectionTest
Public Sub Main()
Dim weights As New Collection
weights.Add("ounces", "oz")
weights.Add("pounds", "lbs")
weights.Add("kilograms", "kg")
weights.Add("milligrams", "mg")
For ordinal As Integer = weights.Count To 1 Step -1
weights.Remove(ordinal)
Next
Console.WriteLine("The collection now has {0} items.",
weights.Count)
End Sub
End Module
165
'Remove from Collection
Public Class Test274
Public Shared Sub Main()
Dim employees As New Collection
employees.Add(New Employee274("A"))
employees.Add(New Manager("B"))
employees.Add(New Manager("C"))
employees.Add(New Employee274("D"))
For Each emp As Employee274 In employees
Console.WriteLine(emp.Name)
Next emp
For i As Integer = employees.Count To 1 Step -1
Dim emp As Employee274 = CType(employees(i),
Employee274)
If emp.IsManager Then employees.Remove(i)
Next i
For Each emp As Employee274 In employees
Console.WriteLine(emp.Name)
Next emp
End Sub
End Class
Public Class Employee274
Public Name As String
Public Sub New(ByVal new_name As String)
Name = new_name
End Sub
Public Overridable Function IsManager() As Boolean
Return False
End Function
End Class
Public Class Customer
Public Name As String
Public Sub New(ByVal new_name As String)
Name = new_name
End Sub
End Class
166
Public Class Manager
Inherits Employee274
Public Sub New(ByVal new_name As String)
MyBase.new(new_name)
End Sub
Public Overrides Function IsManager() As Boolean
Return True
End Function
End Class
'Scanning items in a collection
Public Class Tester275
Public Shared Sub Main()
Dim numberCollection As New Collection
numberCollection.Add(14, "C")
numberCollection.Add(25, "D")
numberCollection.Add(36, "E")
numberCollection.Add(47, "A")
numberCollection.Add(58, "B")
' ----- Scan the collection with a loop counter.
' Collections are base-1, not base-0.
For counter As Integer = 1 To numberCollection.Count
Console.WriteLine(numberCollection(counter))
Next counter
' ----- Scan the collection by item.
For Each number As Integer In numberCollection
Console.WriteLine(number)
Next number
' ----- Retrieve items by key.
Console.WriteLine(numberCollection("A"))
Console.WriteLine(numberCollection("B"))
Console.WriteLine(numberCollection("C"))
Console.WriteLine(numberCollection("D"))
Console.WriteLine(numberCollection("E"))
End Sub
167
End Class
'Add user defined object to ArrayList
Imports System.Collections
Structure Person276
Dim strLastName As String
Dim strFirstName As String
Dim strPhone As String
Dim strEMail As String
End Structure
Public Class Test276
Public Shared Sub Main()
Dim alPersons As New ArrayList
Dim udtPerson As New Person276
'Add the first person.
With udtPerson
.strLastName = "S"
.strFirstName = "J"
.strPhone = "5"
.strEMail = "[email protected]"
End With
alPersons.Add(udtPerson)
'Add the second person.
With udtPerson
.strLastName = "J"
.strFirstName = "S"
.strPhone = "5"
.strEMail = "[email protected]"
End With
alPersons.Add(udtPerson)
'Create the third person.
With udtPerson
.strLastName = "J"
.strFirstName = "K"
.strPhone = "5"
.strEMail = "[email protected]"
End With
'Insert the third person, but first check if they
already exists.
168
If Not alPersons.Contains(udtPerson) Then
alPersons.Insert(1, udtPerson)
End If
'Remove the first person.
alPersons.RemoveAt(0)
'Display the array list values.
Console.WriteLine("The array list contains " &
alPersons.Count & " elements.")
For Each udtPerson In alPersons
Console.WriteLine("NAME: " &
udtPerson.strFirstName & " " & udtPerson.strLastName)
Next udtPerson
End Sub
End Class
'Add different data types to ArrayList
Imports System.Collections
Public Class AddElementsToArrayLista
Public Shared Sub Main()
Dim alist1 As New ArrayList()
alist1.Add("Hello") 'Add a System.String
alist1.Add(714) 'Add a System.Int32
alist1.Add(New DateTime(2003, 1, 1)) 'Add a
System.DateTime
alist1.Add(#1/1/2003#) 'Add a System.DateTime
alist1.Add(4.5) 'Add a System.Double
alist1.Add(4.5F) 'Add a System.Single
Dim o As Object
For Each o In alist1
Console.WriteLine(o & ": " &
o.GetType().ToString())
Next
End Sub
End Class
169
'Use ArrayList to store objects
Option Strict On
Imports System
Imports System.Collections
Public Class Employee278
Private myEmpID As Integer
Public Sub New(ByVal empID As Integer)
Me.myEmpID = empID
End Sub 'New
Public Overrides Function ToString() As String
Return myEmpID.ToString()
End Function 'ToString
Public Property EmpID() As Integer
Get
Return myEmpID
End Get
Set(ByVal Value As Integer)
myEmpID = Value
End Set
End Property
End Class 'Employee
Class Tester278
Shared Sub Main()
Dim empArray As New ArrayList()
Dim intArray As New ArrayList()
Dim i As Integer
For i = 0 To 4
empArray.Add(New Employee278(i + 100))
intArray.Add((i * 5))
Next i
For Each i In intArray
Console.Write("{0} ", i.ToString())
Next i
Console.WriteLine(ControlChars.Lf)
Dim e As Employee
For Each e In empArray
Console.Write("{0} ", e.ToString())
170
Next e
Console.WriteLine(ControlChars.Lf)
Console.WriteLine("empArray.Capacity: {0}",
empArray.Capacity)
End Sub
End Class
'Use For Each to loop through the ArrayList
Imports System.Collections
Structure Person279
Dim strLastName As String
Dim strFirstName As String
Dim strPhone As String
Dim strEMail As String
End Structure
Public Class Test279
Public Shared Sub Main()
Dim alPersons As New ArrayList
Dim udtPerson As New Person279
'Add the first person.
With udtPerson
.strLastName = "S"
.strFirstName = "J"
.strPhone = "5"
.strEMail = "[email protected]"
End With
alPersons.Add(udtPerson)
'Add the second person.
With udtPerson
.strLastName = "J"
.strFirstName = "S"
.strPhone = "5"
.strEMail = "[email protected]"
End With
alPersons.Add(udtPerson)
'Create the third person.
With udtPerson
.strLastName = "J"
171
.strFirstName = "K"
.strPhone = "5"
.strEMail = "[email protected]"
End With
'Insert the third person, but first check if they
already exists.
If Not alPersons.Contains(udtPerson) Then
alPersons.Insert(1, udtPerson)
End If
'Remove the first person.
alPersons.RemoveAt(0)
'Display the array list values.
Console.WriteLine("The array list contains " &
alPersons.Count & " elements.")
For Each udtPerson In alPersons
Console.WriteLine("NAME: " &
udtPerson.strFirstName & " " & udtPerson.strLastName)
Next udtPerson
End Sub
End Class
'Convert ArrayList to array
Imports System.Collections
Public Class Test280
Public Shared Sub Main()
Dim array_list As New ArrayList
array_list.Add("A")
array_list.Add("B")
array_list.Add("C")
' Array object of objects.
Dim astring_array As Array
astring_array = array_list.ToArray()
End Sub
End Class
'Use DirectCast to convert ArrayList to array
172
Imports System.Collections
Public Class Test281
Public Shared Sub Main()
Dim array_list As New ArrayList
array_list.Add("A")
array_list.Add("B")
array_list.Add("C")
' Array of strings.
Dim string_array() As String
string_array =
DirectCast(array_list.ToArray(GetType(String)), String())
End Sub
End Class
'Use ArrayList.Contains to check if a object already exists
Imports System.Collections
Structure Person282
Dim strLastName As String
Dim strFirstName As String
Dim strPhone As String
Dim strEMail As String
End Structure
Public Class Test282
Public Shared Sub Main()
Dim alPersons As New ArrayList
Dim udtPerson As New Person282
'Add the first person.
With udtPerson
.strLastName = "S"
.strFirstName = "J"
.strPhone = "5"
.strEMail = "[email protected]"
End With
alPersons.Add(udtPerson)
'Add the second person.
With udtPerson
.strLastName = "J"
.strFirstName = "S"
.strPhone = "5"
173
.strEMail = "[email protected]"
End With
alPersons.Add(udtPerson)
'Create the third person.
With udtPerson
.strLastName = "J"
.strFirstName = "K"
.strPhone = "5"
.strEMail = "[email protected]"
End With
'Insert the third person, but first check if they
already exists.
If Not alPersons.Contains(udtPerson) Then
alPersons.Insert(1, udtPerson)
End If
'Remove the first person.
alPersons.RemoveAt(0)
'Display the array list values.
Console.WriteLine("The array list contains " &
alPersons.Count & " elements.")
For Each udtPerson In alPersons
Console.WriteLine("NAME: " &
udtPerson.strFirstName & " " & udtPerson.strLastName)
Next udtPerson
End Sub
End Class
'Remove element in an ArrayList by index
Imports System.Collections
Structure Person283
Dim strLastName As String
Dim strFirstName As String
Dim strPhone As String
Dim strEMail As String
End Structure
Public Class Test283
174
Public Shared Sub Main()
Dim alPersons As New ArrayList
Dim udtPerson As New Person283
'Add the first person.
With udtPerson
.strLastName = "S"
.strFirstName = "J"
.strPhone = "5"
.strEMail = "[email protected]"
End With
alPersons.Add(udtPerson)
'Add the second person.
With udtPerson
.strLastName = "J"
.strFirstName = "S"
.strPhone = "5"
.strEMail = "[email protected]"
End With
alPersons.Add(udtPerson)
'Create the third person.
With udtPerson
.strLastName = "J"
.strFirstName = "K"
.strPhone = "5"
.strEMail = "[email protected]"
End With
'Insert the third person, but first check if they
already exists.
If Not alPersons.Contains(udtPerson) Then
alPersons.Insert(1, udtPerson)
End If
'Remove the first person.
alPersons.RemoveAt(0)
'Display the array list values.
Console.WriteLine("The array list contains " &
alPersons.Count & " elements.")
For Each udtPerson In alPersons
Console.WriteLine("NAME: " &
udtPerson.strFirstName & " " & udtPerson.strLastName)
Next udtPerson
End Sub
End Class
175
'SortedList
Imports System.Collections
Public Class Test284
Public Shared Sub Main()
Dim jobs As New SortedList
jobs.Add("02", "Two")
jobs.Add("10", "Ten")
jobs.Add("01", "One")
jobs.Add("06", "Six")
For i As Integer = 0 To jobs.Count - 1
Console.WriteLine(jobs.GetKey(i).ToString() & ": "
& _
jobs.GetByIndex(i).ToString())
Next i
jobs.Clear()
jobs.Add(2, "Two")
jobs.Add(10, "Ten")
jobs.Add(1, "One")
jobs.Add(6, "Six")
For i As Integer = 0 To jobs.Count - 1
Console.WriteLine(jobs.GetKey(i).ToString() & ": "
& _
jobs.GetByIndex(i).ToString())
Next i
End Sub
End Class
'Add value pair to Hashtable and get value back by key
Imports System
Imports System.Collections
176
Class Test285
Shared Sub Main()
Dim myTable As New Hashtable()
myTable.Item("A") = 1
myTable.Item("B") = 44
myTable.Item("C") = 43
myTable.Item("D") = 33
myTable.Item("E") = 39
Dim Country As String = "C"
Dim Code As Integer = myTable.Item(Country)
Console.WriteLine(Code)
End Sub
End Class
'Retrieve single value from Hashtable by key
Option Strict On
Imports System.Collections
Public Module modMain286
Public Sub Main()
Dim airports As New Hashtable
airports.Add("JFK", "John F. Kennedy, New York")
airports.Add("LAX", "Los Angeles International, Los
Angeles")
airports.Add("ORD", "O'Hare International, Chicago")
airports.Add("LHR", "Heathrow Airport, London")
Console.WriteLine(airports.Item("JFK"))
End Sub
End Module
'Find value and key in a Hashtable
177
Imports System.Collections
Public Module Hasher
Dim Tablet As Hashtable = New Hashtable()
Sub Main()
AddToTable()
FindItem("AAA")
FindKey("BBB")
End Sub
Public Sub AddToTable()
Tablet.Add("333", "WWWW")
Tablet.Add("444", "AAA")
Tablet.Add("BBB", "I386")
End Sub
Public Sub FindItem(ByVal item As String)
If Tablet.ContainsValue(item) Then
Console.WriteLine("Found {0} in the hashtable.",
item)
End If
End Sub
Public Sub FindKey(ByVal key As String)
If Tablet.ContainsKey(key) Then
Console.WriteLine("Found {0} in the list.", key)
End If
End Sub
End Module
'Use For Each to loop through all keys in Hashtable
Imports System.Collections
Public Class Test288
Public Shared Sub Main()
Dim myTable As New Hashtable
Dim objKey As Object
Dim objValue As Object
'Populate the hash table.
myTable.Add("H", 1)
myTable.Add("L", 2)
178
'Check before inserting another value.
If Not myTable.ContainsKey("A") Then
myTable.Add("A", 78)
End If
'Remove a value.
myTable.Remove("L")
'Display the hash table values.
Console.WriteLine("The hash table contains " &
myTable.Count & " elements.")
For Each objKey In myTable.Keys
objValue = myTable.Item(objKey)
Console.WriteLine("ELEMENT KEY: " &
objKey.ToString & vbCrLf & _
"ELEMENT VALUE: " & objValue.ToString)
Next objKey
End Sub
End Class
'Queue
Option Strict On
Imports System.Collections
Public Module modMain289
Public Sub Main()
Dim waitingPassengers As New Queue
Console.WriteLine(waitingPassengers.Count)
waitingPassengers.Enqueue("a")
'waitingPassengers.Enqueue("b")
Console.WriteLine(waitingPassengers.Peek())
Console.WriteLine(waitingPassengers.Count)
Console.WriteLine(waitingPassengers.Dequeue())
End Sub
179
End Module
'Enqueue, Dequeue and Peek
Imports System
Imports System.Collections
Class Tester290
Public Sub Run()
End Sub 'Run
Public Shared Sub DisplayValues(ByVal myCollection As
IEnumerable)
Dim myEnumerator As IEnumerator =
myCollection.GetEnumerator()
While myEnumerator.MoveNext()
Console.WriteLine("{0} ", myEnumerator.Current)
End While
Console.WriteLine()
End Sub 'DisplayValues
Shared Sub Main()
Dim intQueue As New Queue()
' populate the array
Dim i As Integer
For i = 0 To 4
intQueue.Enqueue((i * 5))
Next i
' Display the Queue.
Console.WriteLine("intQueue values:")
DisplayValues(intQueue)
' Remove an element from the queue.
Console.WriteLine("(Dequeue) {0}", intQueue.Dequeue())
' Display the Queue.
Console.WriteLine("intQueue values:")
DisplayValues(intQueue)
' Remove another element from the queue.
Console.WriteLine("(Dequeue) {0}", intQueue.Dequeue())
' Display the Queue.
Console.WriteLine("intQueue values:")
180
DisplayValues(intQueue)
' View the first element in the
' Queue but do not remove.
Console.WriteLine("(Peek) {0}", intQueue.Peek())
' Display the Queue.
Console.WriteLine("intQueue values:")
DisplayValues(intQueue)
End Sub 'Main
End Class 'Tester
'Queue.Enqueue and ToArray
Imports System.Collections
Public Class Test291
Private Shared m_Queue As New Queue
Public Shared Sub Main()
m_Queue.Enqueue("A")
DisplayQueue()
m_Queue.Enqueue("B")
DisplayQueue()
m_Queue.Enqueue("C")
DisplayQueue()
Dim txt As String = DirectCast(m_Queue.Dequeue(),
String)
Console.WriteLine(txt)
DisplayQueue()
End Sub
Private Shared Sub DisplayQueue()
For Each str As String In m_Queue.ToArray()
Console.WriteLine(str)
Next str
End Sub
End Class
'Stack
Imports System.Collections
Public Class Test292
Public Shared Sub Main()
Dim txt As String = "asdf"
181
Dim letter_stack As New Stack
For i As Integer = 0 To txt.Length - 1
Console.WriteLine(i)
letter_stack.Push(txt.Substring(i, 1))
Next
'letter_stack.Pop()
Do While letter_stack.Count > 0
Console.WriteLine(DirectCast(letter_stack.Pop(),
String))
Loop
End Sub
End Class
'Stack: Push, Pop and Peek
Option Strict On
Imports System
Imports System.Collections
Class Tester293
Public Shared Sub DisplayValues(ByVal myCollection As
IEnumerable)
Dim o As Object
For Each o In myCollection
Console.WriteLine(o)
Next o
End Sub 'DisplayValues
Shared Sub Main()
Dim intStack As New Stack()
' populate the stack
Dim i As Integer
For i = 0 To 7
intStack.Push((i * 5))
Next i
' Display the Stack.
Console.WriteLine("intStack values:")
DisplayValues(intStack)
' Remove an element from the stack.
182
Console.WriteLine("(Pop){0}", intStack.Pop())
' Display the Stack.
Console.WriteLine("intStack values:")
DisplayValues(intStack)
' Remove another element from the stack.
Console.WriteLine("(Pop){0}", intStack.Pop())
' Display the Stack.
Console.WriteLine("intStack values:")
DisplayValues(intStack)
' View the first element in the
' Stack but do not remove.
Console.WriteLine("(Peek) {0}", intStack.Peek())
' Display the Stack.
Console.WriteLine("intStack values:")
DisplayValues(intStack)
End Sub 'Main
End Class 'Tester
'Convert and Copy Elements in a Stack to an Array
Option Strict On
Imports System
Imports System.Collections
Class Tester294
Public Shared Sub DisplayValues(ByVal myCollection As
IEnumerable)
Dim o As Object
For Each o In myCollection
Console.WriteLine(o)
Next o
End Sub
Shared Sub Main()
Dim intStack As New Stack()
Dim i As Integer
For i = 1 To 4
intStack.Push((i * 5))
Next i
183
Console.WriteLine("intStack values:")
DisplayValues(intStack)
Const arraySize As Integer = 10
Dim testArray(arraySize) As Integer
For i = 1 To arraySize - 1
testArray(i) = i * 100
Next i
Console.WriteLine("Contents of the test array")
DisplayValues(testArray)
intStack.CopyTo(testArray, 3)
Console.WriteLine("TestArray after copy: ")
DisplayValues(testArray)
Dim myArray As Object() = intStack.ToArray()
Console.WriteLine("The new array:")
DisplayValues(myArray)
End Sub
End Class
'Using generic methods to print arrays of different types
Module Tester295
Sub Main()
Dim integerArray As Integer() = {1, 2, 3, 4, 5, 6}
Dim doubleArray As Double() = {1.1, 2.2, 3.3, 4.4,
5.5, 6.6, 7.7}
Dim charArray As Char() = {"H"c, "E"c, "L"c, "L"c,
"O"c}
PrintArray(integerArray)
PrintArray(doubleArray)
PrintArray(charArray)
End Sub
Public Sub PrintArray(Of E)(ByVal inputArray() As E)
For Each element As E In inputArray
Console.Write(element.ToString() & " ")
Next element
184
Console.WriteLine(vbCrLf)
End Sub
End Module
'WithEvents and Event method
Public Class Tester296
Shared WithEvents Click3 As New TripleClicker
Public Shared Sub Main()
Click3.Click()
Click3.Click()
Click3.Click()
End Sub
Private Shared Sub Click3_TplClick(ByVal Text As String)
Handles Click3.TplClick
Console.WriteLine(Text)
End Sub
End Class
Public Class TripleClicker
Public Event TplClick(ByVal Text As String)
Public Sub Click()
Static intCount As Integer = 0
intCount += 1
If intCount >= 3 Then
intCount = 0
RaiseEvent TplClick("The button was triple
clicked.")
End If
End Sub
End Class
'File Creation, Last Write and Last Access time
185
Imports System.IO
Public Class Tester297
Public Shared Sub Main()
Console.WriteLine(File.GetCreationTime("test.vb"))
Console.WriteLine(File.GetLastWriteTime("test.vb"))
Console.WriteLine(File.GetLastAccessTime("test.vb"))
End Sub
End Class
'File Exists
Imports System.IO
Public Class Tester298
Public Shared Sub Main()
Console.WriteLine(File.Exists("test.vb"))
End Sub
End Class
'File's Attributes
Option Strict On
Imports System.IO
Public Module FileSystemAttributes
Public Sub Main()
Dim docPath As String =
My.Computer.FileSystem.SpecialDirectories.MyDocuments
186
For Each fn As String In
My.Computer.FileSystem.GetFiles(docPath)
Dim fi As FileInfo = New FileInfo(fn)
Console.WriteLine("{0}: {1}", fi.Name,
fi.Attributes.ToString())
Next
End Sub
End Module
'FileAttributes
Public Class Test300
Public Shared Sub Main()
Dim lngAttributes As Long
lngAttributes =
System.IO.File.GetAttributes("test.txt")
' Use a binary AND to extract the specific attributes.
Console.WriteLine("Normal: " & CBool(lngAttributes And
IO.FileAttributes.Normal))
Console.WriteLine("Hidden: " & CBool(lngAttributes And
IO.FileAttributes.Hidden))
Console.WriteLine("ReadOnly: " & CBool(lngAttributes
And IO.FileAttributes.ReadOnly))
Console.WriteLine("System: " & CBool(lngAttributes And
IO.FileAttributes.System))
Console.WriteLine("Temporary File: " &
CBool(lngAttributes And IO.FileAttributes.Temporary))
Console.WriteLine("Archive: " & CBool(lngAttributes
And IO.FileAttributes.Archive))
End Sub
End Class
187
'Copy a file
Imports System.IO
Imports System.Text
Public Class Tester301
Public Shared Sub Main()
Dim mySourceFileStream As FileStream
Dim myDestFileStream As FileStream
Dim bteRead() As Byte
Dim intByte As Integer
Dim bteMessage(128) As Byte
Dim strCopyMessage As String = ""
Try
myDestFileStream = New FileStream("dest.txt",
FileMode.OpenOrCreate, FileAccess.Write)
bteMessage =
Encoding.ASCII.GetBytes(strCopyMessage)
myDestFileStream.Write(bteMessage, 0,
bteMessage.Length)
mySourceFileStream = New FileStream("source.txt",
FileMode.OpenOrCreate, FileAccess.Read)
intByte = mySourceFileStream.Length
ReDim bteRead(intByte)
mySourceFileStream.Read(bteRead, 0, intByte)
myDestFileStream.Write(bteRead, 0, intByte)
myDestFileStream.Close()
mySourceFileStream.Close()
Catch ex As IOException
Console.WriteLine(ex.Message)
End Try
End Sub
End Class
'Delete a file with kill
188
Public Class Tester302
Public Shared Sub Main()
Kill("Test.csv")
End Sub
End Class
'Delete a file
Imports System.IO
Public Class Tester303
Public Shared Sub Main()
Dim f6 As File
f6.Delete("test.txt")
End Sub
End Class
'Move a file with File.Move
Imports System.IO
Public Class Tester305
Public Shared Sub Main()
Dim f35 As File
File.Move("test.txt", "text2.txt")
End Sub
End Class
'Use FreeFile
Option Strict On
189
Public Module Checking
Private Const filename As String = "CheckFile.dat"
Public Sub Main()
Dim fn As Integer = FreeFile
Dim fileOpened As Boolean
Try
FileOpen(fn, filename, OpenMode.Append)
fileOpened = True
WriteLine(fn, 1605, Date.Now, "Books", 2.19)
Catch e As Exception
Console.WriteLine(e.GetType().Name & ": " &
e.Message)
Finally
If fileOpened Then FileClose(fn)
End Try
End Sub
End Module
'FileMode.OpenOrCreate
Imports System.IO
Public Class Tester307
Public Shared Sub Main()
Dim fs As System.IO.FileStream
Dim w As System.IO.BinaryWriter
Dim buffer As String
Dim c As Char
c = Chr(9)
fs = New System.IO.FileStream("test.txt",
IO.FileMode.OpenOrCreate)
w = New System.IO.BinaryWriter(fs)
w.Seek(0, System.IO.SeekOrigin.Begin)
w.Write("writing data via BinaryWriter")
w.Close()
fs.Close()
End Sub
End Class
190
'FileMode.Open with FileAccess.Read
Imports System.IO
Public Class Tester308
Public Shared Sub Main()
Dim f As System.IO.FileStream
Dim r As System.IO.StreamReader
Dim mylength As Integer
Dim i As Integer
f = New System.IO.FileStream("test.txt",
IO.FileMode.Open, IO.FileAccess.Read)
r = New System.IO.StreamReader(f)
Console.WriteLine(r.ReadToEnd())
f.Close()
r.Close()
End Sub
End Class
'Path.GetInvalidPathChars
Imports System.IO
Public Class Test309
Public Shared Sub Main()
For Each ch As Char In Path.GetInvalidPathChars()
Console.WriteLine(ch)
Next ch
End Sub
End Class
'Path.GetInvalidFileNameChars
191
Imports System.IO
Public Class Test310
Public Shared Sub Main()
For Each ch As Char In Path.GetInvalidFileNameChars()
Console.WriteLine(ch)
Next ch
End Sub
End Class