Constructors

In Chapter 8, notice that the statement that creates the Time object looks as though it is invoking a Time() method:

 Time timeObject = new Time();

In fact, a member method is invoked whenever you instantiate an object. This method is called a constructor. Each time you define a class, you are free to define your own constructor, but if you don’t, the compiler will provide one for you invisibly and automatically.

The job of a constructor is to create an instance of the object specified by a class and to put it into a valid state. Before the constructor runs, the object is just a blob of memory; after the constructor completes, the memory holds a valid instance of the class.

The Time class of Example 8-3 does not define a constructor. As noted earlier, if you do not declare a constructor the compiler implicitly provides one for you. The constructor provided by the compiler creates the object but takes no other action.

Tip

Any constructor that takes no arguments is called a default constructor. The constructor provided by the compiler takes no arguments, and hence is a default constructor. This terminology has caused a great deal of confusion. You can create your own default constructor, and if you do not create a constructor at all, the compiler will create a default constructor for you, by default.

If you do not explicitly initialize your member variables, they are initialized to innocuous values (integers to 0, strings to the empty string, etc.). Table 8-2 lists ...

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.