Previous section   Next section

5.4 Initializers

It is possible to initialize the values of member variables with an initializer, instead of having to do so in the constructor. You create an initializer by assigning an initial value to a class member:

Private second As Integer = 30

Assume that the semantics of the Time object are such that no matter what time is set, the seconds are always initialized to 30. You might rewrite your Time class to use an initializer so that the value of Second is always initialized, as shown in Example 5-6.

Example 5-6. Using an initializer
Option Strict On
Imports System

Public Class Time
   ' Private variables
   Private year As Integer
   Private month As Integer
   Private date As Integer
   Private hour As Integer
   Private minute As Integer
   Private second As Integer = 30
   ' Public methods
   Public Sub DisplayCurrentTime( )
        Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", _
            month, date, 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
      date = theDate
      hour = theHour
      minute = theMinute
   End Sub


End Class 'Time

Module Module1

   Sub Main( )
      Dim timeObject As New Time(2005, 3, 25, 9, 35)
      timeObject.DisplayCurrentTime( )
   End Sub

End Module


Output:
3/25/2005 9:35:30

If you do not provide a specific initializer, the constructor will initialize each integer member variable to zero (0). In the case shown, however, the Second member is initialized to 30:

Private second As Integer = 30

  Previous section   Next section
Top