The Default Constructor

Introduction

A constructor of a class is a special method with two main rules and one primary feature:

ApplicationPractical Learning: Introducing Constructors

  1. Start Microsoft Visual Studio
  2. On the Visual Studio 2019 dialog box, click Create a New Project (if Microsoft Visual Studio is already opened, on the main menu, click File -> New -> Project...)
  3. In the list of projects templates of the Create a New Project dialog box, click Windows Forms App (.NET Framework)
  4. Create Next
  5. Change the project Name to Chemistry01
  6. Click Create
  7. Design the form as follows:

    Values Conversion - Metric System

    Control (Name) Text
    Label   Symbol:
    TextBox txtSymbol
    Label   Element Name:
    TextBox txtElementName
    Label   Atomic Number:
    TextBox txtAtomicNumber
    Label   Atomic Weight:
    TextBox txtAtomicWeight

Introduction to the Default Constructor

A constructor is a special method that is created when the object comes to life. When you create a class, if you don't create a constructor, the compiler creates one for you. This compiler-created constructor is called the default constructor. If you want, you can create your own default constructor.

To initiate a constructor, create a method that holds the same name as the class and that doesn't return any value. Here is an example:

class Square
{
    Square()
    {
    }
}

Remember that any method that doesn't have an access level is considered private. This is also valid for constructors. Although you can have private constructors in very extreme scenarios, most of the constructors you will create or use must be public (or internal). Here is an example:

class Square
{
    public Square()
    {
    }
}

If you are using Microsoft Visual Studio, to create a default constructor, right-click inside the class and click Insert Snippet... Double-click Visual C#. In the list that appears, double-click ctor:

Constructor

The Code Editor would use the name of the class to create the new method

When you create an object of the class (by declaring a variable of that class), whether you use that object or not, a constructor for the object is created. When an instance of a class has been declared, the default constructor is called, whether the object is used or not. This is illustrated in the following program:

public class BankAccount
{
    public BankAccount()
    {
        System.Console.WriteLine("New Bank Account");
    }
}

public class Exercise
{
    static void Main()
    {
        BankAccount account = new BankAccount();
    }
}

This would produce:

New Bank Account
Press any key to continue . . .

As you can see, even though the object was not used, just its creation was enough to call the default constructor. You may find it sometimes convenient to create your own constructor because, whether you create a default constructor or not, this does not negatively impact your program.

ApplicationPractical Learning: Using the Default Constructor

  1. On the main menu, click Project -> Add Class...
  2. In the middle list of Add New Item dialog box, make sure Class is selected. Click Add
  3. Right-click in the Code Editor and click Remove and Sort Usings
  4. In the class, add the following fields:
    namespace Chemistry01
    {
        class Class1
        {
            internal string Name;
            internal string Symbol;
            internal int AtomicNumber;
            internal double AtomicWeight;
        }
    }

Initializing the Members of a Class

If a class has a default constructor, when an object is created from that class, that default constructor is automatically called. This feature makes the default constructor a good place to initialize the members of the class. You have many options.

When creating a class, you can declare a member variable and initialize it in the body of the class. Here are examples:

public class Element
{
    int AtomicNumber = 1;
}

Remember that a member created without the access level (public, private, or internal) is treated as private, and to re-inforce this, you can precede the member with the private keyword:

public class Element
{
    private int AtomicNumber = 1;
}

In the same way, you can declare and initialize as many members as you want in the body of the class. Here are examples:

public class Element
{
    string Symbol = "H";
    int AtomicNumber = 1;
}

As an alternative, you can fields in the class, then create a constructor and initialize the field(s) in the constructor.

ApplicationPractical Learning: Creating a Constructor that Initializes

Creating an Object Using a Constructor

As we have seen since Lesson 3, to create an object, declare a variable of a class. As we saw in Lesson 3 and in this lesson, if the class doesn't have any constructor or it has a default constructor, initialize the object using the default constructor. When accessing each member from the object variable, you can use the period operator.

ApplicationPractical Learning: Creating an Object Using a Constructor

  1. Click the Form1.cs [Design] tab to access the form
  2. Right-click the form and click View Code
  3. Right-click in the Code Editor and click Remove and Sort Usings
  4. Create two methods as follows:
    using System.Windows.Forms;
    
    namespace Chemistry01
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
    
                Class1 elm = new Class1();
    
                txtElementName.Text = elm.Name;
                txtSymbol.Text = elm.Symbol;
                txtAtomicNumber.Text = elm.AtomicNumber.ToString();
                txtAtomicWeight.Text = elm.AtomicWeight.ToString();
            }
        }
    }
  5. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging

    Calling a Method of One Parameter

  6. Close the form and return to your programming environment
  7. In the Solution Explorer, right-click Class1 and click Rename
  8. Type Element to get Element.cs
  9. Press Enter
  10. Read the text in the message box and click Yes

Initializing an Object

With or without a constructor, you can specify the values of an object at any time. This means that, even if a class has a default constructor and you have created its object, to set the values of the members of the class, access each member and assign the desired value.

ApplicationPractical Learning: Initializing an Object

  1. In the Solution Explorer, right-click Form1.cs and click Rename
  2. Type Chemistry to get Chemistry.cs
  3. Press Enter
  4. Read the text in the message box and click Yes
  5. To create and initialize an object, change the code of the form as follows:
    using System.Windows.Forms;
    
    namespace Chemistry01
    {
        public partial class Chemistry : Form
        {
            public Chemistry()
            {
                InitializeComponent();
    
                Element he = new Element();
    
                he.Symbol = "He";
                he.Name = "Helium";
                he.AtomicNumber = 2;
                he.AtomicWeight = 4.002602;
    
                txtElementName.Text = he.Name;
                txtSymbol.Text = he.Symbol;
                txtAtomicNumber.Text = he.AtomicNumber.ToString();
                txtAtomicWeight.Text = he.AtomicWeight.ToString();
    
                Text = "Chemistry - Helium";
            }
        }
    }
  6. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging

    The Default Constructor of a Class

  7. Close the form and return to your programming environment
  8. As an alternative, you can declare a variable and initialize it with the default constructor. Between the closing parenthesis and the semicolon, add the curly brackets that delimit a body in C#. In the curly brackets, add the name of a member of the class and initialize it with the value of your choice. Do the same for other desired members. You don't have to initialize each member and you don't have to list the members in the same order they appear in the class. The initializations must be separated by commas.
    For examples, change the code as follows:
    using System.Windows.Forms;
    
    namespace Chemistry01
    {
        public partial class Chemistry : Form
        {
            public Chemistry()
            {
                InitializeComponent();
    
                Element he = new Element();
    
                he.Symbol = "He";
                he.Name = "Helium";
                he.AtomicNumber = 2;
                he.AtomicWeight = 4.002602;
    
                Element li = new Element() { Name = "Lithium", AtomicWeight = 6.94, AtomicNumber = 3, Symbol = "Li" };
    
                txtElementName.Text = li.Name;
                txtSymbol.Text = li.Symbol;
                txtAtomicNumber.Text = li.AtomicNumber.ToString();
                txtAtomicWeight.Text = li.AtomicWeight.ToString();
    
                Text = "Chemistry - Lithium";
            }
        }
    }
  9. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging

    The Default Constructor of a Class

  10. Close the form and return to your programming environment
  11. To make your code easier to read, you can put each curly bracket on its own line. You can also initialize each member on its own line.
    For an example, change the code as follows:
    using System.Windows.Forms;
    
    namespace Chemistry01
    {
        public partial class Chemistry : Form
        {
            public Chemistry()
            {
                InitializeComponent();
    
                Element he = new Element();
    
                he.Symbol = "He";
                he.Name = "Helium";
                he.AtomicNumber = 2;
                he.AtomicWeight = 4.002602;
    
                Element li = new Element() { Name = "Lithium", AtomicWeight = 6.94, AtomicNumber = 3, Symbol = "Li" };
                
                Element be = new Element()
                {
                    AtomicNumber = 4,
                    Name = "Beryllium",
                    AtomicWeight = 9.0121831,
                    Symbol = "Be"
                };
    
                txtElementName.Text = be.Name;
                txtSymbol.Text = be.Symbol;
                txtAtomicNumber.Text = be.AtomicNumber.ToString();
                txtAtomicWeight.Text = be.AtomicWeight.ToString();
    
                Text = "Chemistry - Beryllium";
            }
        }
    }
  12. To execute the project, press Ctrl + F5:

    The Default Constructor of a Class

  13. Close the form and return to your programming environment

The Constructor as a Method

A Constructor with a Parameter

In your class, you can create a constructor that uses a parameter. Here is an example:

public class Square
{
    public Square(double side)
    {

    }
}

In the body of the class, you can ignore or use the parameter. One way you can use it is to pass its value to a member variable of the class. Here is an example:

public class Square
{
    private double s;

    public Square(double side)
    {
        s = side;
    }
}

Remember that the other members, such as methods, of the class can access any member of the same class. After creating the class, you can declare variables of it.

If you create a class with only one constructor as in the above example, when declaring an instance of the class, you must use that constructor: you cannot use the default constructor that doesn't use a parameter. When declaring the variable, initialize it with a constructor with parentheses and provide the value(s) in the parentheses of the constructor.

ApplicationPractical Learning: Using the Default Constructor

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the list of projects templates, click Windows Forms App (.NET Framework)
  3. Click Next
  4. Change the project Name to Geometry02
  5. Click Create
  6. On the main menu, click Project -> Add Class
  7. Set the name as Figure
  8. Click Add
  9. Right-click in the Code Editor and click Remove and Sort Usings
  10. Change the class as follows:
    namespace Geometry02
    {
        class Figure
        {
            private double s;
    
            public Figure(double side)
            {
                s = side;
            }
    
            public double CalculatePerimeter()
            {
                return s * 4;
            }
    
            public double CalculateArea()
            {
                return s * s;
            }
        }
    }
  11. In the Solution Explorer, right-click Form1.cs and click Rename
  12. Type Geometry to get Geometry.cs
  13. Press Enter
  14. Read the text of the message box and click Yes
  15. In the Solution Explorer, double-click Geometry.cs to access the form
  16. Design the form as follows:

    Values Conversion - Metric System

    Control (Name) Text Other Properties
    Label   Side:  
    TextBox txtSide 0.00 TextAlign: Right
    Button btnCalculate Calculate  
    Label   Perimeter:  
    TextBox txtPerimeter   TextAlign: Right
    Label   Area:  
    TextBox txtArea TextAlign: Right
  17. On the form, double-click the Calculate button
  18. Right-click in the Code Editor and click Remove and Sort Usings
  19. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry02
    {
        public partial class Geometry : Form
        {
            public Geometry()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double side = double.Parse(txtSide.Text);
    
                Figure sqr = new Figure(side);
    
                double perimeter = sqr.CalculatePerimeter();
                double area = sqr.CalculateArea();
    
                txtPerimeter.Text = perimeter.ToString();
                txtArea.Text = area.ToString();
            }
        }
    }
  20. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging

    A Parameterized Constructor

  21. In the Side text box, type a number such as 248.73

    A Parameterized  Constructor of a Class

  22. Click the button

    A Parameterized Constructor of a Class

  23. Close the form and return to your programming environment
  24. On the main menu, click File -> Recent Projects and Solutions -> Chemistry01

A Constructor with Many Parameters

In your class, you can create a constructor with as many parameters as you want. Here is an example of a constructor that uses three parameters:

public class Exercise
{
    public Exercise(string a, int b, int c)
    {
    }
}

In the body of the constructor, you can ignore or use the values of the parameters. To create an object of the class, declare a variable of the class and initialize it using the constructor. This means that you must pass an argument for each parameter.

ApplicationPractical Learning: Using a Constructor with Many Parameters

  1. Click the Element.cs tab to access a certain class. Change it as follows:
    namespace Chemistry01
    {
        class Element
        {
            internal string ElementName;
            internal string Symbol;
            internal int AtomicNumber;
            internal double AtomicWeight;
    
            public Element(int number, string symbol, string name, double mass)
            {
                Symbol = symbol;
                ElementName = name;
                AtomicWeight = mass;
                AtomicNumber = number;
            }
        }
    }
  2. Click the Chemistry.cs tab and change the code of the Click event as follows:
    using System.Windows.Forms;
    
    namespace Chemistry01
    {
        public partial class Chemistry : Form
        {
            public Chemistry()
            {
                InitializeComponent();
    
                Element h  = new Element(1, "H",  "Hydrogen",  1.008);
                Element he = new Element(2, "He", "Helium",    4.002602);
                Element li = new Element(3, "Li", "Lithium",   6.94);
                Element be = new Element(4, "Be", "Beryllium", 9.0121831);
                Element b  = new Element(5, "B",  "Boron",    10.81);
    
                txtElementName.Text = b.ElementName;
                txtSymbol.Text = b.Symbol;
                txtAtomicNumber.Text = b.AtomicNumber.ToString();
                txtAtomicWeight.Text = b.AtomicWeight.ToString();
    
                Text = "Chemistry - Boron";
            }
        }
    }
  3. To execute the application and see the result, on the main menu, click Debug -> Start Without Debugging

    A Parameterized Constructor

  4. Close the form and return to your programming environment

Passing an Argument by Name

As seen with methods, if you call a constructor that takes many arguments, you can access each parameter by its name, followed by a colon, and its value.

ApplicationPractical Learning: Passing Arguments by Names

  1. Change the code as follows:
    using System.Windows.Forms;
    
    namespace Chemistry01
    {
        public partial class Chemistry : Form
        {
            public Chemistry()
            {
                InitializeComponent();
    
                Element h  = new Element(1, "H",  "Hydrogen",  1.008);
                Element he = new Element(2, "He", "Helium",    4.002602);
                Element li = new Element(3, "Li", "Lithium",   6.94);
                Element be = new Element(4, "Be", "Beryllium", 9.0121831);
                Element b  = new Element(5, "B",  "Boron",    10.81);
                Element c  = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6);
    
                txtElementName.Text  = c.ElementName;
                txtSymbol.Text       = c.Symbol;
                txtAtomicNumber.Text = c.AtomicNumber.ToString();
                txtAtomicWeight.Text = c.AtomicWeight.ToString();
    
                Text = "Chemistry - Carbon";
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debuggin

    A Parameterized Constructor

  3. Close the form and return to your programming environment

Constructor Overloading

In your class, you can create as many constructors as you want. If you decide to create different constructors, they must follow the rules of method overloading. This means that each constructor must be different from the others. To take care of this, each constructor can use a different number of parameters or different data types for parameters compared to other constructors. Here are examples:

using System.Windows.Forms;

public class Exercise
{
    public Exercise(string a)
    {
    }

    public Exercise(string a, int b, int c)
    {
    }
}

If you create different constructors, when declaring a (the) variable(s) for the class, you can choose what constructor is appropriate to initialize the variable.

ApplicationPractical Learning: Passing Arguments by Names

  1. Click the Element.cs tab and change its class as follows:
    namespace Chemistry01
    {
        class Element
        {
            internal string ElementName;
            internal string Symbol;
            internal int AtomicNumber;
            internal double AtomicWeight;
    
            public Element(int number)
            {
                AtomicNumber = number;
            }
    
            public Element(string symbol)
            {
                Symbol = symbol;
            }
    
            public Element(int number, string symbol, string name, double mass)
            {
                Symbol = symbol;
                ElementName = name;
                AtomicWeight = mass;
                AtomicNumber = number;
            }
        }
    }
  2. Click the Chemistry.cs tab and change the code of the Click event as follows:
    using System.Windows.Forms;
    
    namespace Chemistry01
    {
        public partial class Chemistry : Form
        {
            public Chemistry()
            {
                InitializeComponent();
    
                Element h  = new Element(1, "H",  "Hydrogen",  1.008);
                Element he = new Element(2, "He", "Helium",    4.002602);
                Element li = new Element(3, "Li", "Lithium",   6.94);
                Element be = new Element(4, "Be", "Beryllium", 9.0121831);
                Element b  = new Element(5, "B",  "Boron",    10.81);
                Element c  = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6);
    
                Element n = new Element(7);
                n.Symbol = "N";
                n.AtomicWeight = 14.007;
                n.ElementName = "Nitrogen";
    
                txtElementName.Text  = n.ElementName;
                txtSymbol.Text       = n.Symbol;
                txtAtomicNumber.Text = n.AtomicNumber.ToString();
                txtAtomicWeight.Text = n.AtomicWeight.ToString();
    
                Text = "Chemistry - Nitrogen";
            }
        }
    }
  3. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Overloading a Constructor

  4. Close the form and return to your programming environment

The Absence of a Default Constructor

If you create a class with only one constructor and that constructor uses at least one parameter, the default constructor would not be available anymore. If you want to access a default constructor of an object, you have two options:

A class is usually made to contain many members. The primary reason you create a constructor is to have a tool to initialize an object of the class with one or some default values. The primary reason you create different constructors is to provide different values to objects depending on what constructor a user (actually a programmer) wants to use to create an object. To make this happen, you can initialize the members with values passed to the parameter(s). Here are examples:

using System.Windows.Forms;

public class Exercise
{
    Form frmExercise;

    public Exercise()
    {
        frmExercise = new Form();

        frmExercise.Text = "World Annotation";
        frmExercise.Width = 800;
        frmExercise.Height = 640;
    }

    public Exercise(string caption)
    {
        frmExercise = new Form();

        frmExercise.Text = caption;
        frmExercise.Width = 358;
        frmExercise.Height = 636;
    }

    public Exercise(string caption, int width)
    {
        frmExercise = new Form();

        frmExercise.Width = width;
        frmExercise.Text = caption;
    }

    public Exercise(string caption, int width, int height)
    {
        frmExercise = new Form();

        frmExercise.Width = width;
        frmExercise.Height = height;
        frmExercise.Text = caption;
    }
}

A Constructor with Default Values

Since a constructor is primarily a method, its parameter(s), if any, can use default values. The rules are exactly the same we reviewed for methods. To provide a default value for the parameter of a constructor, assign the desired but appropriate value to the parameter when creating the constructor. Here is an example:

public class Exercise
{
    public Exercise(string caption = "Exercise")
    {
    }
}

Once again, in the body of the constructor, you can use or ignore the parameter. If you create one constructor and it uses one parameter, when creating an object of the class, that single constructor would act as both (or either) a default constructor and (or) a constructor that uses one parameter. This means that you can declare a variable and use a constructor with empty parentheses. Here is an example:

using System.Windows.Forms;

public class Exercise
{
    public Exercise(string caption = "Exercise")
    {
        Form frmExercise = new Form();

        frmExercise.Text = caption;
    }
}

public class Program
{
    static void Main()
    {
        Exercise first = new Exercise();
    }
}

In the same way, you can create a constructor that uses different parameters and some parameters can have default values. When doing this, make sure you follow the rules we reviewed for methods that have default values for parameters. Here is an example:

using System.Windows.Forms;

public class Exercise
{
    public Exercise(string caption = "Exercise", int width = 640, int height = 480)
    {
        Form frmExercise = new Form();

        frmExercise.Width = width;
        frmExercise.Height = height;
        frmExercise.Text = caption;
    }
}

public class Program
{
    static void Main()
    {
        Exercise first = new Exercise();
        Exercise second = new Exercise("Employment Application");
        Exercise third = new Exercise("Student Registration", 1224);
        third = new Exercise("Student Registration", 824, 479);
        third = new Exercise(width : 545, height : 258, caption : "Introductory Learning");
    }
}

The Destruction of an Object

The Destructor of a Class

As opposed to a constructor, a destructor is called when a program has finished using an object. A destructor does the cleaning behind the scenes. Like the default constructor, the compiler always creates a default destructor if you don't create one. Unlike the constructor, the destructor cannot be overloaded. This means that, if you decide to create a destructor, you can have only one. Like the default constructor, a destructor also has the same name as its class. This time, the name of the destructor starts with a tilde "~".

To create a destructor, type ~ followed by the name of the class. Here is an example:

public class Exercise
{
    public Exercise(string caption = "Exercise", int width = 640, int height = 480)
    {
    }

    ~Exercise()
    {
    }
}

Garbage Collection

When you initialize a variable using the new operator, you are in fact reserving some space in the section of memory called the heap. Such memory is "allocated" for the variable. When that variable is no longer needed, such as when your program closes, the variable must be removed from memory and the space it was using should (must) be made available to other variables or other programs. In fact, when an object has been removed from memory, it is replaced by garbage, which is some value but that is of no use (that area of memory becomes filled with garbage). If you program in some languages such as C/C++, Assembly, Pascal, etc, you should (must) find a way to remove that garbage (it is not difficult, sometimes it takes a simple/single line of code, but you should (must) remember to do it); that is, you should (must) free the memory a variable (declared with new, and called a reference) was using. Freeing the memory is referred to as garbage collection. Normally, in languages like C++ or Pascal, that's one of the ways you use a destructor.

The .NET Framework solves the problem of garbage collection by "cleaning" the memory after you. This is done automatically when necessary so that the programmer doesn't need to worry about this issue.

ApplicationPractical Learning: Ending the Lesson


Previous Copyright © 2001-2021, C# Key Next