10.1. Constructors

You should think of constructors as methods that are designed to create, or instantiate, an object. The sole purpose of a constructor is to enable you to instantiate an object with a known state. The beauty of C# (and most other OOP languages) is that you get a default constructor automatically.

10.1.1. Default Constructors

To make the creation of a default constructor possible, a constructor always has the same name as its class. For example, if you wish to create an object named myDate of the clsDates class, you would use the following statement:

clsDates myDate = new clsDate();

I've talked about this syntax before, but let's dig a little deeper now.

First, notice that the leftmost reference to clsDates is simply the name of the class: no closing parentheses follow the class name. In effect, this reference to clsDates is simply telling you which cookie cutter to take from the thousands of them hanging on the wall.

Second, the purpose of the identifier myDate is to enable you to give a name to the reference variable that your code uses as a link to the data for the clsDates class. You learned in Chapter 5 that the rvalue of a reference variable is either null or the memory address of the location of the data for the object. For learning purposes, you can think of myDate as having the rvalue of null at this instant in time.

Third, the keyword new should always jog your memory and make you remember that there are going to be some messages exchanged between your ...

Get Beginning C# 3.0 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.