Skip to Content
Programming Visual Basic .NET, Second Edition
book

Programming Visual Basic .NET, Second Edition

by Jesse Liberty
April 2003
Intermediate to advanced
560 pages
14h 4m
English
O'Reilly Media, Inc.
Content preview from Programming Visual Basic .NET, Second Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Visual Basic .NET

Programming Visual Basic .NET

Dave Grundgeiger
VB.NET Language in a Nutshell, Second Edition

VB.NET Language in a Nutshell, Second Edition

Steven Roman PhD, Ron Petrusha, Paul Lomax

Publisher Resources

ISBN: 0596004389Supplemental ContentCatalog PageErrata