need a little help with constructors

  • Thread starter Thread starter Stephen
  • Start date Start date
S

Stephen

Im new to VB.net....Im having a problem understandign how a constructor relates to the base form and a class.

What is the function on the constructor ..does it accept variables passed to it from the form?

Steve
 
* "Stephen said:
Im new to VB.net....Im having a problem understandign how a
constructor relates to the base form and a class.

What is the function on the constructor ..does it accept variables
passed to it from the form?

Please don't post in HTML format.

The constructor gets called when the instance of the class is created.
It contains "initialization" code. First, the base class's constructor
will be called (you can do this explicitly by calling 'MyBase.New()'),
then you can execute your own initialization code. You can parameterize
the constructor to privide data to the initialization process.
 
Stephen,
In addition to Herfried's comments.

If you used classes in VB6 the constructor is similar to the
Class_Initialize event. In that they are both executed when the object is
created, allowing you to ensure that the class is fully initialized when it
is created.

The advantage that VB.NET's constructors have over VB6's Class Initialize
event is that you can parameterize them! Which means you cannot create an
instance of the object without supplying all the parameters to the
constructor. You can also add code to the constructor to validate the
parameters!

To define a constructor in VB.NET you add a 'Sub New' to your class or
structure. The constructor is always called 'New' in VB.NET.

For example the following Person class requires a name when you create a
person object, this name cannot be Nothing, nor can it be an empty string.
The person's name cannot be changed later.

Public Class Person

Private Readonly m_name As String

Public Sub New(ByVal name As String)
If name Is Nothing Then
Throw New ArgumentNullException("name", "Name cannot be
nothing")
ElseIf name = String.Empty Then
Throw New ArgumentOutOfRangeException("name", name, "Name
cannot be an empty")
End If
m_name = name
End Sub

Public Readonly Property Name() As String
Get
Return m_name
End Get
End Property

Public Overrides Function ToString() As String
Return String.Format("Person({0})", m_name)
End Function

End Class

Dim jay As New Person("Jay")
Dim herfried As Person
person = New Person("Herfried")

Robin A. Reynolds-Haertle's book "OOP with Microsoft Visual Basic .NET and
Microsoft Visual C# .NET - Step by Step" from MS Press covers this plus the
rest of OOP in VB.NET, in a very straight forward manner.

Hope this helps
Jay

Im new to VB.net....Im having a problem understandign how a constructor
relates to the base form and a class.

What is the function on the constructor ..does it accept variables passed to
it from the form?

Steve
 
Back
Top