CSCI 1301

Constructors

1. Learning Objectives

  • What are constructors
  • How to declare constructors
  • Overloading constructors

2. What are Constructors

Constructor is a special class member that gets called when an object is instantiated - that is, when you first create an object. It will not get called at any other point in time. In fact there is no syntax that enables you to call it at any other point in time.

Class constructor is used for

  • initializing class data members and
  • to perform other setup steps

Constructor is invoked by the new operator immediately after memory is allocated for the new object.

Default Constructor

Classes without constructors are given a public, parameterless constructor by the C# compiler in order to enable class instantiation. This default constructor instantiates the object and sets member variables to their default values.

So far all classes we have implemented have used this default parameterless constructor. When we want to perform more advanced setup steps for class objects, we must define our own constructors. Note that when you define constructors, the default parameterless constructor will no longer be created for you. It is also not required to define a parameterless constructor.

3. Declaring Class Constructors in C#

A constructor is a method whose name is the same as the name of its type, i.e. class name. Constructor method signature includes only:

  • access modifier
  • the method name
  • its parameter list

It does NOT include a return type.

The following demonstrates a very simple constructor with 0 parameters:

MyClassWithMethods.cs
1public class TestClass{
2
3 // this is a parameterless constructor
4 // you can tell it is a constructor
5 // because its name matches class name
6 // and there is no return type
7 public TestClass(){ }
8
9}

Notice:

  • constructor access modifier is (usually) public
  • there is no return type
  • constructor method name matches class name

You can identify a constructor because it meets the above criteria.

4. Initializing Class Members Using a Constructor

Constructors are used for initializing class properties. We have seen an earlier implementation of a class where all properties were set to their default values. We could then change the property values by calling setters for each property. While this strategy works, we can simply the program and guarantee that values are initialized in a systematic way by using a constructor. Using a constructor also allows us to enforce rules to require initial information must be provided before an object is can be created.

Consider this example:

1public class User{
2
3 private string name;
4 private int age;
5
6 // constructor
7 public User(string name, int age){
8 this.name = name; // initialize name
9 this.age = age; // initialize age
10 }
11}
12
13public class Program{
14
15 public static void Main(){
16
17 // this command is OK
18 User andy = new User("Andy", 30);
19
20 // this will not work because
21 // constructor requires 2 parameters!
22 User joe = new User();
23
24 }
25}

The example above shows a class called User with a custom constructor that has two required parameters. Notice how inside the constructor we initialize name and age fields with the values we receive from the caller.

Recall that when we define a custom constructor for a class, the default parameterless constructor no longer exists. Therefore we cannot create a user joe without providing the required information name and age. When calling constructors the number and type of parameters must match (same as methods).

1public class User{
2
3 private string name;
4 private int age;
5
6 // constructor
7 public User(string name, int age){
8 this.name = name; // initialize name
9 this.age = age; // initialize age
10 }
11}
12
13public class Program{
14
15 public static void Main(){
16
17 // this command is OK
18 User andy = new User("Andy", 30);
19
20 // now this command is OK also
21 User joe = new User("Joe", 25);
22
23 }
24}

After providing required arguments, it will match the class constructor, and we can successfully instantiate the object to represent joe.

5. Constructor Overloading

So far we have created classes with no custom constructors and classes with 1 custom constructors. But there may be times where we want to create multiple custom constructors within a single class to support different ways of initializing objects. This is called constructor overloading.

The following example demonstrates constructor overloading:

User class now has 4 different constructors:

  • Parameterless constructor (line 7) this constructor doesn't do anything
  • Constructor that with one string parameter (line 10) initializes name with the provided value
  • Constructor that with one int parameter (line 15) initializes age with the provided value
  • Constructor with two parameters (line 20) initializes both name and age with the provided values

This implementation allows us to use any of these constructors when instantiating objects.

How does the compiler know which constructor to use?

It determines the correct one by matching the number, order, and type of parameters. For example,

  • if you create a user and provide two arguments, it will use the constructor with two parameters
  • if you provide no arguments, the parameterless constructor will get called.
  • When you provide just one argument
    • if the argument is int type, constructor on line 15 will be called
    • If the argument is string type, constructor on line 10 will be called.

You can define an unlimited number of constructors for a class, but they must all have unique signatures to allow for the compiler to determine which one to use. You will encounter an error if you create ambiguous constructors whereby the compiler does not know which one to use. I encourage you to experiment with this.

6. Further Examples

If constructor parameter names match class field names, use keyword this within a constructor.

1public class Person{
2
3 private string first;
4 private string last;
5
6 public Person(string first, string last){
7 this.first = first;
8 this.last = last;
9 }
10}

When the constructor parameter names are different from class field names, we do not need keyword this

1public class Person{
2
3 private string first;
4 private string last;
5
6 public Person(string firstName, string lastName){
7 first = firstName;
8 last = lastName;
9 }
10}

You may also perform more advanced operations while initializing class members as shown below. Notice the class constructor is overloaded and there are two valid ways to instantiate an object.

1public class Employee{
2
3 private int salary;
4
5 public Person(int annualSalary){
6 salary = annualSalary;
7 }
8
9 public Person(int weeklySalary, int numberOfWeeks){
10 salary = weeklySalary * numberOfWeeks;
11 }
12}
13
14
15public class Program{
16
17 public static void Main(){
18
19 // which constructor gets called here?
20 Employee e1 = new Employee(30000);
21
22 // which constructor gets called here?
23 Employee e2 = new Employee(500, 52);
24
25 }
26}

7. Summary

What are constructors?

Constructors are special methods called when an object is instantiated. They are used for initializing class members and to perform other setup steps.

How to declare constructors

define: access modifier (typically public), identifier that matches the class name, and a list of parameters. No return type.

Overloading constructors

You can create multiple constructors for a single class, allowing multiple different ways to instantiate an object. This is called (constructor) overloading. Each constructor must have a distinct method signature.