Working WinForms Example
The following example demonstrates using a constructor to initialize a public member field.
Create a form and place a button on it and alter the code as follows:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim MyRobot As New Cyborg("Cameron")
MessageBox.Show("My robot's name is " & MyRobot.CyborgName & ".")
End Sub
End Class
Public Class Cyborg
Public CyborgName As String
Public Sub New(ByVal pName As String)
CyborgName = pName
End Sub
End Class
Overloading Constructors
Here is a working example of overloading a constructor. In this example, we overload our New() constructor so you can either pass in a name or set the name after creation.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim MyRobot1 As New Cyborg()
MyRobot1.CyborgName = "John"
MessageBox.Show("My robot's name is " & MyRobot1.CyborgName & ".")
Dim MyRobot2 As New Cyborg("Cameron")
MessageBox.Show("My robot's name is " & MyRobot2.CyborgName & ".")
End Sub
End Class
Public Class Cyborg
Public CyborgName As String
Public Sub New()
End Sub
Public Sub New(ByVal pName As String)
CyborgName = pName
End Sub
End Class