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 int Second = 30; // initializer

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

Example 7-4. Using an initializer

using System;

public class Time
{
   // private member variables
   int year;
   int month;
   int date;
   int hour;
   int minute;
   int second = 30;

   // public method
   public void DisplayCurrentTime( )
   {
      System.Console.WriteLine( "{0}/{1}/{2} {3}:{4}:{5}",
      month, date, year, hour, minute, second );
   }

   // constructor
   public Time( int theYear, int theMonth, int theDate,
   int theHour, int theMinute )
   {
      year = theYear;
      month = theMonth;
      date = theDate;
      hour = theHour;
      minute = theMinute;
   }
}

public class Tester
{
   static void Main( )
   {
      Time timeObject = new Time( 2008, 8, 1, 9, 35 );
      timeObject.DisplayCurrentTime( );
   }
}

The output looks like this:

    8/1/2008 9:35:30

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

    private int Second = 30; // initializer

Later in this chapter, you will see that you can have more than one constructor. If you assign 30 to Second in more than one of these, you can avoid the problem of having to keep all the constructors consistent with one another by initializing the Second member, rather than assigning 30 in each of the constructors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset