Home > Articles > Programming > C#

This chapter is from the book 

4.10 Initializing Objects with Constructors

As mentioned in Section 4.5, when a GradeBook (Fig. 4.7) object is created, its instance variable courseName is initialized to null by default. This is also true of the private instance variable that the compiler creates for the auto-implemented CourseName property discussed in Section 4.8. What if you want to provide a course name when you create a GradeBook object? Each class can provide a constructor that can be used to initialize an object of a class when the object is created. In fact, C# requires a constructor call for every object that's created. The new operator calls the class's constructor to perform the initialization. The constructor call is indicated by the class name, followed by parentheses. For example, line 11 of Fig. 4.8 first uses new to create a GradeBook object. The empty parentheses after "new GradeBook()" indicate a call without arguments to the class's constructor. The compiler provides a public default constructor with no parameters in any class that does not explicitly define a constructor, so every class has a constructor. The default constructor does not modify the default values of the instance variables.

When you declare a class, you can provide your own constructor (or several constructors, as you'll learn in Chapter 10) to specify custom initialization for objects of your class. For example, you might want to specify a course name for a GradeBook object when the object is created, as in

            GradeBook myGradeBook =
  new GradeBook( "CS101 Introduction to C# Programming" );

In this case, the argument "CS101 Introduction to C# Programming" is passed to the GradeBook object's constructor and used to initialize the CourseName. Each time you create a new GradeBook object, you can provide a different course name. The preceding statement requires that the class provide a constructor with a string parameter. Figure 4.12 contains a modified GradeBook class with such a constructor.

Fig 4.12. GradeBook class with a constructor to initialize the course name.

 1  // Fig. 4.12: GradeBook.cs
 2  // GradeBook class with a constructor to initialize the course name.
 3  using System;
 4
 5  public class GradeBook
 6  {
 7     // auto-implemented property CourseName implicitly created an
 8     // instance variable for this GradeBook's course name
 9     public string CourseName { get; set; }
10
11     // constructor initializes auto-implemented property
12     // CourseName with string supplied as argument      
13     public GradeBook( string name )                     
14     {                                                   
15        CourseName = name;  // set CourseName to name    
16     }  // end constructor                               
17
18     // display a welcome message to the GradeBook user
19     public void DisplayMessage()
20     {
21        // use auto-implemented property CourseName to get the
22        // name of the course that this GradeBook represents
23        Console.WriteLine( "Welcome to the grade book for\n{0}!",
24           CourseName );
25     }  // end method DisplayMessage
26  }  // end class GradeBook

Lines 13–16 declare the constructor for class GradeBook. A constructor must have the same name as its class. Like a method, a constructor specifies in its parameter list the data it requires to perform its task. When you use new to create an object, you place this data in the parentheses that follow the class name. Unlike a method, a constructor doesn't specify a return type (not even void). Line 13 indicates that class GradeBook's constructor has a parameter called name of type string. In line 15, the name passed to the constructor is used to initialize auto-implemented property CourseName via its set accessor.

Figure 4.13 demonstrates initializing GradeBook objects using this constructor. Lines 12–13 create and initialize a GradeBook object. The constructor of class GradeBook is called with the argument "CS101 Introduction to C# Programming" to initialize the course name. The object-creation expression to the right of = in lines 12–13 returns a reference to the new object, which is assigned to variable gradeBook1. Lines 14–15 repeat this process for another GradeBook object, this time passing the argument "CS102 Data Structures in C#" to initialize the course name for gradeBook2. Lines 18–21 use each object's CourseName property to obtain the course names and show that they were indeed initialized when the objects were created. In Section 4.5, you learned that each instance (i.e., object) of a class contains its own copy of the class's instance variables. The output confirms that each GradeBook maintains its own course name.

Fig 4.13. GradeBook constructor used to specify the course name at the time each GradeBook object is created.

 1  // Fig. 4.13: GradeBookTest.cs
 2  // GradeBook constructor used to specify the course name at the
 3  // time each GradeBook object is created.
 4  using System;
 5
 6  public class GradeBookTest
 7  {
 8     // Main method begins program execution
 9     public static void Main( string[] args )
10     {
11        // create GradeBook object
12        GradeBook gradeBook1 = new GradeBook( // invokes constructor
13           "CS101 Introduction to C# Programming" );                
14        GradeBook gradeBook2 = new GradeBook( // invokes constructor
15           "CS102 Data Structures in C#" );                         
16
17        // display initial value of courseName for each GradeBook
18        Console.WriteLine( "gradeBook1 course name is: {0}",
19           gradeBook1.CourseName );
20        Console.WriteLine( "gradeBook2 course name is: {0}",
21           gradeBook2.CourseName );
22     }  // end Main
23  }  // end class GradeBookTest

Normally, constructors are declared public. If a class does not explicitly define a constructor, the class's instance variables are initialized to their default valuesβ€”0 for numeric types, false for type bool and null for reference types. If you declare any constructors for a class, C# will not create a default constructor for that class.

Adding the Constructor to Class GradeBook's UML Class Diagram

The UML class diagram of Fig. 4.14 models class GradeBook of Fig. 4.12, which has a constructor that has a name parameter of type string. Like operations, the UML models constructors in the third compartment of a class in a class diagram. To distinguish a constructor from a class's operations, the UML places the word "constructor" between guillemets (Β« and Β΅) before the constructor's name. It's customary to list constructors before other operations in the third compartment.

Fig. 4.14

Fig. 4.14 UML class diagram indicating that class GradeBook has a constructor with a name parameter of type string.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.