Section 8.4. Initializers

   

8.4 Initializers

It is possible to initialize the values of member variables in 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 8-6.

Example 8-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( )         System.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  
   


Learning Visual Basic. NET
Learning Visual Basic .Net
ISBN: 0596003862
EAN: 2147483647
Year: 2002
Pages: 153
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net