Module Module1
Sub Main()
Console.WriteLine("***** Fun with Operator Overloading *****" & vbLf)
AddSubtractMyPointsWithMethodCalls()
Console.WriteLine("Calling sub AddSubtractMyPointsWithOperators()")
AddSubtractMyPointsWithOperators()
Console.WriteLine("Calling sub testPointsForEquality()")
TestMyPointsForEquality()
Console.WriteLine("Calling sub TestMyPointsForGreaterLessThan()")
TestMyPointsForGreaterLessThan()
Console.ReadLine()
End Sub
Sub AddSubtractMyPointsWithMethodCalls()
Dim p As New MyPoint(10, 10)
Dim p2 As New MyPoint(20, 30)
'add two MyPoints using Add() method
Dim newPoint = MyPoint.Add(p, p2)
Console.WriteLine("p + p2 = {0}", newPoint)
'subtract two MyPoints using Subtract() method
Console.WriteLine("p - p2 = {0}", MyPoint.Subtract(p, p2))
End Sub
Sub AddSubtractMyPointsWithOperators()
Dim p As New MyPoint(10, 10)
Dim p2 As New MyPoint(20, 30)
'really calls: MyPoint.Operator+(p, p2)
Dim newPoint As MyPoint = p + p2
Console.WriteLine("p + p2 = {0}", newPoint)
'really calls: MyPoint.Operator -(p, p2)
Console.WriteLine("p - p2 = {0}", p - p2)
End Sub
'make use of the overloaded equality operators
Sub TestMyPointsForEquality()
Dim ptOne As New MyPoint(10, 2)
Dim ptTwo As New MyPoint(10, 44)
Console.WriteLine("ptOne = ptTwo : {0}", ptOne = ptTwo) 'false
Console.WriteLine("ptOne <> ptTwo : {0}", ptOne <> ptTwo) 'true
End Sub
Sub TestMyPointsForGreaterLessThan()
Dim ptOne As New MyPoint(5, 2)
Dim ptTwo As New MyPoint(5, 44)
Console.WriteLine("ptOne > ptTwo: {0}", ptOne > ptTwo) 'false
Console.WriteLine("ptOne < ptTwo: {0}", ptOne < ptTwo) ' false
Console.WriteLine("ptOne >= ptTwo: {0}", ptOne >= ptTwo) 'true
Console.WriteLine("ptOne <= ptTwo: {0}", ptOne <= ptTwo) 'true
End Sub
End Module
Public Structure MyPoint
Implements IComparable
Private x As Integer, y As Integer
Public Sub New(ByVal xPos As Integer, ByVal yPos As Integer)
x = xPos
y = yPos
End Sub
Public Overrides Function ToString() As String
Return String.Format("[{0}, {1}]", Me.x, Me.y)
End Function
'adding two MyPoint objects to yield a new MyPoint
Public Shared Function Add(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As MyPoint
Return New MyPoint(p1.x + p2.x, p1.y + p2.y)
End Function
'better yet, overload operator +
Public Shared Operator +(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As MyPoint
Return New MyPoint(p1.x + p2.x, p1.y + p2.y)
End Operator
'subtratcting two MyPoint objects to yield a new MyPoint
Public Shared Function Subtract(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As MyPoint
Return New MyPoint(p1.x - p2.x, p1.y - p2.y)
End Function
'better yet, overload operator -
Public Shared Operator -(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As MyPoint
Return New MyPoint(p1.x - p2.x, p1.y - p2.y)
End Operator
'overriden methods of system.Object
Public Overrides Function Equals(ByVal obj As Object) As Boolean
If TypeOf obj Is MyPoint Then
If Me.ToString() = obj.ToString() Then
Return True
End If
End If
Return False
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.ToString().GetHashCode()
End Function
'now lets overload the = and <> operators
Public Shared Operator =(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return p1.Equals(p2)
End Operator
Public Shared Operator <>(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return Not p1.Equals(p2)
End Operator
Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
If TypeOf obj Is MyPoint Then
Dim p As MyPoint = CType(obj, MyPoint)
If Me.x > p.x AndAlso Me.y > p.y Then
Return 1
End If
If Me.x < p.x AndAlso Me.y < p.y Then
Return -1
Else
Return 0
End If
Else
Throw New ArgumentException()
End If
End Function
'the overloaded comparison ops
Public Shared Operator <(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return (p1.CompareTo(p2) < 0)
End Operator
Public Shared Operator >(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return (p1.CompareTo(p2) > 0)
End Operator
Public Shared Operator <=(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return (p1.CompareTo(p2) <= 0)
End Operator
Public Shared Operator >=(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return (p1.CompareTo(p2) >= 0)
End Operator
End Structure
Module Module1
Sub Main()
ValueTypesRefTypesAndAssignment()
End Sub
Sub ValueTypesRefTypesAndAssignment()
Console.WriteLine("***** Value Types and the Assignment Operator *****")
Console.WriteLine("-> Creating p1")
Dim p1 As New MyPoint(100, 100)
Console.WriteLine("-> Assigning p2 to p1")
Dim p2 As MyPoint = p1
'here is p1
Console.WriteLine("p1.x = {0}", p1.x)
Console.WriteLine("p1.y = {0}", p1.y)
'here is p2
Console.WriteLine("p2.x = {0}", p2.x)
Console.WriteLine("p2.y = {0}", p2.y)
'change p2.x this will NOT change p1.x
Console.WriteLine("-> Changing p2.x to 900")
p2.x = 900
'print again
Console.WriteLine("-> Here are the X values again...")
Console.WriteLine("p1.x = {0}", p1.x)
Console.WriteLine("p2.x = {0}", p2.x)
Console.ReadLine()
End Sub
End Module
Module Module1
Sub Main()
'create the first MyRectangle
Console.WriteLine("-> Creating r1")
Dim r1 As New MyRectangle("this is my first rect")
'now assign a new MyRectangle to r1
Console.WriteLine("-> Assigning r2 to r1")
Dim r2 As MyRectangle
r2 = r1
'change values of r2
Console.WriteLine("-> Changing all values of r2")
r2.rectInfo.infoString = "This is new info!"
r2.bottom = 4444
'print values
Console.WriteLine("-> Values after change:")
Console.WriteLine("-> r1.rectInfo.infoString: {0}", r1.rectInfo.infoString)
Console.WriteLine("-> r2.rectInfo.infoSTring: {0}", r2.rectInfo.infoString)
Console.WriteLine("-> r1.bottom: {0}", r1.bottom)
Console.WriteLine("-> r2.bottom: {0}", r2.bottom)
Console.ReadLine()
End Sub
End Module
Public Class Person
Public fullName As String
Public age As Integer
Public Sub New(ByVal n As String, ByVal a As Integer)
fullName = n
age = a
End Sub
Public Sub New()
End Sub
Public Overrides Function ToString() As String
Return String.Format("Name: {0}, Age: {1}", fullName, age)
End Function
End Class
Module Module1
Sub SendAPersonByValue(ByVal p As Person)
'change the age of 'p'?
p.age = 99
p = New Person("Nikki", 999)
End Sub
Sub SendAPersonByReference(ByRef p As Person)
'change some data of "p"
p.age = 555
'"p" is now point to a new object on the heap!
p = New Person("Nikki", 999)
End Sub
Sub Main()
'passing ref types by value
Console.WriteLine("***** Passing Person object by value *****" & vbLf)
Dim fred As New Person("Fred", 12)
Console.WriteLine("Before by value call, Person is:")
Console.WriteLine(fred)
SendAPersonByValue(fred)
Console.WriteLine("After by value call, Person is:")
Console.WriteLine(fred)
Console.WriteLine("***** Passing Person object by reference *****")
Dim mel As New Person("Mel", 23)
Console.WriteLine("Before by ref call, Person is:")
Console.WriteLine(mel)
SendAPersonByReference(mel)
Console.WriteLine("After by ref call, Person is:")
Console.WriteLine(mel)
Console.ReadLine()
Console.ReadLine()
End Sub
End Module
Public Class Base
End Class
Public Class Derived
Inherits Base
End Class
Module Program
Sub Main()
'implicit cast between derived to base
Dim myBaseType As Base
myBaseType = New Derived()
'must explicitly cast to store base reference
'in derived tpye
Dim myDerivedType As Derived = CType(myBaseType, Derived)
End Sub
End Module
Public Structure Rectangle
'public for ease of use
Public width As Integer, Height As Integer
Public Sub Draw()
Console.WriteLine("Drawing a rect.")
End Sub
Public Overrides Function ToString() As String
Return String.Format("[Width = {0}; Height = {1}]", width, Height)
End Function
Public Shared Widening Operator CType(ByVal s As Square) As Rectangle
Dim r As Rectangle
r.Height = s.Length
'assume the length of the new Rectangle with (Length X 2)
r.width = s.Length * 2
Return r
End Operator
End Structure
Public Structure Square
Public Length As Integer
Public Sub Draw()
Console.WriteLine("Drawing a square")
End Sub
Public Overrides Function ToString() As String
Return String.Format("[Length = {0}]", Length)
End Function
'rectangls can be explicitly converted
'into squares
Public Shared Narrowing Operator CType(ByVal r As Rectangle) As Square
Dim s As Square
s.Length = r.width
Return s
End Operator
Public Shared Narrowing Operator CType(ByVal sideLength As Integer) As Square
Dim newSq As Square
newSq.Length = sideLength
Return newSq
End Operator
Public Shared Narrowing Operator CType(ByVal s As Square) As Integer
Return s.Length
End Operator
End Structure
Module Module1
Sub DrawSquare(ByVal sq As Square)
sq.Draw()
End Sub
Sub Main()
Console.WriteLine("***** Fun with Custom Conversions *****")
Console.WriteLine()
'create a 10 * 5 rectangle
Dim rect As Rectangle
rect.width = 10
rect.Height = 5
Console.WriteLine("rect = {0}", rect)
'convert rectangle to a 10 * 10 square
Dim sq As Square = CType(rect, Square)
Console.WriteLine("sq = {0}", sq)
'this is all right, as the Square has a custom narrowing CType() implementation
DrawSquare(CType(rect, Square))
'converting an integer to a square
Dim sq2 As Square = CType(90, Square)
Console.WriteLine("sq2 = {0}", sq2)
'converting a square to an integer
Dim side As Integer = CType(sq2, Integer)
Console.WriteLine("Side length of sq2 = {0}", side)
'implicit cast ok!
Dim s3 As Square
s3.Length = 83
Dim rect2 As Rectangle = s3
Console.WriteLine("rect2 = {0}", rect2)
DrawSquare(s3)
'explicit cast syntax ok!
Dim s4 As Square
s4.Length = 3
Dim rect3 As Rectangle = CType(s4, Rectangle)
Console.WriteLine("rect3 = {0}", rect3)
Console.ReadLine()
End Sub
End Module
Imports System
Imports System.Net
Namespace Apress.VisualBasicRecipes.Chapter11
Public Class Recipe11_08
Public Shared Sub Main()
Dim args As String() = {"www.apress.com", "www.microsoft.com", "www.cracked.com"}
For Each comp As String In args
Try
'retrieve the DNS entry for the specified computer
Dim dnsEntry As IPHostEntry = dNS.GetHostEntry(comp)
'the dns entry may contain more thant one IP address iterate through
'them and display each one along with the type of address
For Each address As IPAddress In dnsEntry.AddressList
Console.WriteLine("{0} = {1} ({2})", comp, address, address.AddressFamily)
Next
Catch ex As Exception
Console.WriteLine("{0} = Error ({1})", comp, ex.Message)
End Try
Next
Console.ReadLine()
End Sub
End Class
End Namespace
Imports System
Imports System.Net.NetworkInformation
Namespace Apress.VisualBasicRecipes.Chapter11
Public Class Recipe11_09
Public Shared Sub Main()
Dim args As String() = {"www.cracked.com"}
'crate an instance of the Ping class
Using png As New Ping
Console.WriteLine("Pringing:")
For Each comp As String In args
Try
Console.Write("{0}...", comp)
'ping the specified computer with a time-out of 100ms
Dim reply As PingReply = png.Send(comp, 100)
If reply.Status = IPStatus.Success Then
Console.WriteLine("Success - IP Address:{0} " & "Time:{1}ms", reply.Address, reply.RoundtripTime)
Else
Console.WriteLine(reply.Status.ToString)
End If
Catch ex As Exception
Console.WriteLine("Error ({0})", ex.InnerException.Message)
End Try
Next
End Using
Console.ReadLine()
End Sub
End Class
End Namespace
Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Namespace Apress.VisualBasicRecipes.Chapter11
Public Class Recipe11_10Shared
Public Const AcknowledgeOK As String = "OK"
Public Const AcknowledgeCancel = "Cancel"
Public Const Disconnect As String = "Bye"
Public Const RequestConnect As String = "Hello"
End Class
Public Class Recipe11_10Server
Public Shared Sub Main()
'create a listener on port 8000
Dim listener As New TcpListener(IPAddress.Parse("127.0.0.1"), 8000)
Console.WriteLine("About to initialize port")
listener.Start()
Console.WriteLine("Listening for a connection...")
Try
'wait for a connection request and return a TcpClient initialized for communication
Using client As TcpClient = listener.AcceptTcpClient
Console.WriteLine("Connection accepted")
'retrieve the network stream
Dim stream As NetworkStream = client.GetStream()
'create a binarywriter for writing to the stream
Using w As New BinaryWriter(stream)
'create a binaryReader for reading from the stream
Using r As New BinaryReader(stream)
If r.ReadString = Recipe11_10Shared.RequestConnect Then
w.Write(Recipe11_10Shared.AcknowledgeOK)
Console.WriteLine("Connection completed.")
While Not r.ReadString = Recipe11_10Shared.Disconnect
End While
Console.WriteLine(Environment.NewLine)
Console.WriteLine("Disconnect request receieved.")
Else
Console.WriteLine("Can't complete connection.")
End If
End Using
End Using
End Using
Console.WriteLine("Connection closed.")
Catch ex As Exception
Console.WriteLine(ex.ToString)
Finally
'close the underlying socket (stop listening for new requests)
listener.Stop()
Console.WriteLine("Listener stopped.")
End Try
Console.ReadLine()
End Sub
End Class
End Namespace
Option Strict On
Imports System
Imports System.Collections
Namespace Enumeration
Public Class ListBoxTest : Implements IEnumerable
Private strings() As String
Private ctr As Integer = 0
'private nested implementation of ListBoxEnumerator
Private Class ListBoxEnumerator
Implements IEnumerator
'member fields of the nested ListBoxEnumerator class
Private currentListBox As ListBoxTest
Private index As Integer
'public within the private implementation
'thus private within ListBoxTest
Public Sub New(ByVal currentListBox As ListBoxTest)
'a particular ListBoxTest instance is passed in, hold a reference to it
'in the member variable currentListBox
Me.currentListBox = currentListBox
index = -1
End Sub
'incremement the index and make sure the value is valid
Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
index += 1
If index >= currentListBox.strings.Length Then
Return False
Else
Return True
End If
End Function
Public Sub Reset() Implements IEnumerator.Reset
index = -1
End Sub
Public ReadOnly Property Current As Object Implements System.Collections.IEnumerator.Current
Get
Return currentListBox(index)
End Get
End Property
End Class 'end nested class
'enumerable classes can return an enumerator
Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return New ListBoxEnumerator(Me)
End Function
'initialize the list box with strings
Public Sub New(ByVal ParamArray initialStrings() As String)
'allocate space for the strings
ReDim strings(7)
'copy the strings passed in to the constructor
Dim s As String
For Each s In initialStrings
strings(ctr) = s
ctr += 1
Next
End Sub
'add a single string to the end of the list box
Public Sub add(ByVal theString As String)
strings(ctr) = theString
ctr += 1
End Sub
'allow array-like access
Default Public Property Item(ByVal index As Integer) As String
Get
If index < 0 Or index >= strings.Length Then
'handle bad index
Exit Property
End If
Return strings(index)
End Get
Set(ByVal value As String)
strings(index) = value
End Set
End Property
'publish how many strings you hold
Public Function GetNumEntries() As Integer
Return ctr
End Function
End Class
Public Class Tester
Public Sub Run()
'create a new lst box and initialize
Dim currentListBox As New ListBoxTest("Hello", "World")
'add a few strings
currentListBox.add("Who")
currentListBox.add("Is")
currentListBox.add("John")
currentListBox.add("Galt")
'test the access
Dim subst As String = "Universe"
currentListBox(1) = subst
'access all the string
Dim s As String
For Each s In currentListBox
Console.WriteLine("Value: {0}", s)
Next
End Sub
Shared Sub Main()
Dim t As New Tester()
t.Run()
Console.ReadLine()
End Sub
End Class
End Namespace
Option Strict On
Imports System
Namespace ArrayListDemo
'a class to hold in the array list
Public Class Employee
Private myEmpID As Integer
Public Sub New(ByVal empID As Integer)
Me.myEmpID = empID
End Sub
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 Tester
Public Sub Run()
Dim empArray As New ArrayList()
Dim intArray As New ArrayList()
'populate the arraylists
Dim i As Integer
For i = 0 To 4
empArray.Add(New Employee(i + 100))
intArray.Add((i * 5))
Next i
'print each member of the array
For Each i In intArray
Console.Write("{0} ", i.ToString())
Next i
Console.WriteLine(ControlChars.Lf)
'print each employee
For Each e In empArray
Console.WriteLine("{0} ", e.ToString())
Next
Console.WriteLine(ControlChars.Lf)
Console.WriteLine("empArray.Capacity: {0}", empArray.Capacity)
End Sub 'Run
Shared Sub Main()
Dim t As New Tester()
t.Run()
Console.ReadLine()
End Sub
End Class
End Namespace