Team LiB   Previous Section   Next Section

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

Example 8-5. 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(2005,3,25,9,35); 
        timeObject.DisplayCurrentTime();
    }
}
 Output:
3/25/2005 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 initialize Second to 30 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.

    Team LiB   Previous Section   Next Section