본문 바로가기
Visual Basic .NET/Class

how to Initialize Class Member Variables

by edupicker(체르니) 2008. 6. 24.

Initializing Class Member Variables

When you create a class object, you will normally immediately assign values to specific class member variables.

For example, the following code fragment defines a Person class that contains fields for a Name, Age, OfficeNumber, and CellularPhoneNumber:


Class Person

    Public Name As String

    Public Age As Integer

    Public OfficeNumber As String

    Public CellularPhoneNumber As String

End Class

 

Within your program, you can create (instantiate) instances of the Person class, which programmers refer to as objects, using the following statement:

Dim thePerson As New Person ()

 

To simplify the process of initializing class member variables, you can place a special subroutine within your class definition (named New) that Visual Basic .NET automatically calls each time you create a class object.
Programmers refer to this special subroutine as a “constructor” because it helps

you build (construct) the class object.

The constructor method is special in that within any class definition, the constructor is always named New.
Programmers use the constructor to initialize class member variables.

The following code fragment, for example, extends the Person class to include the New constructor method:

Class Person

             Public Name As String

             Public Age As Integer

             Public OfficeNumber As String

             Public CellularPhoneNumber As String

 

             Sub New(ByVal PesonName As String, ByVal PersonAge As Integer, _

                               ByVal PersonOfficeNumber As String, _
                               ByVal Person
CellularPhoneNumber As String)


                          
Name = PesonName

                           Age = PersonAge

                           OfficeNumber = PersonOfficeNumber

                           CellularPhoneNumber = PersonCellularPhoneNumber

                           MsgBox("Name: " & PesonName & " Age: " & PersonAge & _

                                           " OfficeNumber: " & PersonOfficeNumber & _
                                           “CellularPhoneNumber:” &
PersonCellularPhoneNumber )

             End Sub

End Class

 

Well, I made a windows application sample using messagebox to display the results.

I attached the sample files on this article.
I hope the article helps to you.