IMPORTANT PLEASE READ!
Website development and design blog, tutorials and inspiration

C# Class Constructors and Destructors

A look at class constructors and destructors

By , Written on in C#

C# Class Constructors and Destructors

890 words, estimated reading time 5 minutes.

Class constructors and destructors are methods that are automatically called when a class is instantiated or destroyed. They are provided so that the class can be initialized with the correct data, open connections and so on and also to finalise and close connections and files before the object is removed from memory.
 
C# Programming Series
  1. Introduction to Programming
  2. What is C#?
  3. Your First Console Application in C#
  4. Introducing Methods and the Main() Function in C#
  5. Introducing C# Classes and Structs
  6. C# Data Types, Variables and Casting
  7. C# Program Flow Control and Entry Points
  8. Passing Parameters to Methods and Return Values in C#
  9. C# Access Modifiers and Scope
  10. C# Interfaces and Classes
  11. Using Namespaces in C#
  12. C# Conditional Statements
  13. Looping and Iteration in C#
  14. Using Arrays and Lists in C#
  15. C# Constants and Read-Only Variables
  16. Error and Exception Handling in C#
  17. Using Recursion in C#
  18. C# Operator List
  19. Class Inheritance in C#
  20. C# Class and Method Attributes Explained
  21. C# Class Constructors and Destructors
  22. C# Generics Variables
  23. XML Serialization and Deserialization
  24. C# String Formatting Examples

You do not need to provide a constructor method in your classes as the compiler will automatically initialize fields to default values using a default constructor which takes no parameters. A constructor should be used when you need non-default values to be initialized. Constructors can also be overloaded to extend the functionality of the method. If you do create an overloaded constructor, the compiler will not provide a default, so if you still require a constructor with no parameters you must provide it yourself.

A constructor is declared as a public method with the same name as the class. In these examples, we are going to continue using the car classes from the previous tutorial. I have added the baseCarClass() constructor to the example, as shown below.

  1. class baseCarClass
  2. {
  3. public bool isEngineRunning;
  4. public decimal speed;
  5. public decimal distanceTraveled;
  6. public decimal fuelLevel;
  7. public Color colour;
  8.  
  9. // Constructor
  10. public baseCarClass()
  11. {
  12. }
  13.  
  14. public void startEngine()
  15. {
  16. }
  17.  
  18. void accelerate()
  19. {
  20. }
  21.  
  22. void brake()
  23. {
  24. }
  25.  
  26. void stopEngine()
  27. {
  28. }
  29. }

When you compile your class, the compiler will automatically add a default "hidden" constructor for you, however, if you want to provide additional functionality then you must do this yourself. When instantiating the class with the new keyword you can pass a parameter to the constructor.

  1. // Constructor
  2. public baseCarClass(Color carColour)
  3. {
  4. colour = carColor;
  5. }
  1. baseCarClass car = new baseCarClass(Color.Yellow);
  2. //car.colour == Color.Yellow
  3.  
  4. baseCarClass car = new baseCarClass(); // Will not compile
  5.  

As soon as you code a constructor, the compiler will not automatically provide one for you. Only those coded will be present, so if you create a constructor with a parameter you will not be able to create an object with a parameterless constructor unless you write one.

This example constructor will only allow a baseCarClass to be created when a colour is given. The default with no parameters is not available. If you do need it, you will have to create it yourself.

  1. // Default Constructor
  2. public baseCarClass()
  3. {
  4. // Call the most specific constructor to prevent duplicate code
  5. baseCarClass(Color.Black);
  6. }
  7.  
  8. // Custom Constructor
  9. public baseCarClass(Color carColour)
  10. {
  11. colour = carColour;
  12. }
  1. baseCarClass car = new baseCarClass(Color.Yellow);
  2. //car.colour == Color.Yellow
  3.  
  4. baseCarClass car = new baseCarClass(); // Now will compile
  5. //car.colour == Color.Black - default color
  6.  

Constructors and Inheritance

By default all inherited classes will use the constructor as the base class, unless overridden (more on this in a later tutorial).

Because the constructor was added to the baseCarClass, any class inheriting from it can also benefit from having the constructor, thus:

  1. SportsCar sporty = new SportsCar(Color.Pink);
  2. //sporty.colour == Color.Pink

To create a constructor specifically for the SportsCar class we define it in the same way:

  1. // Constructor
  2. public SportsCar(bool roofUp)
  3. {
  4. isRoofUp = roofUp;
  5. }
  1. SportsCarcar = new SportsCar(true);
  2. //car.isRoofUp == true

What colour is the SportsCar?

Because we have not provided a colour in our constructor, the default constructor for the base class has been called making the colour of the car Color.Black. You can call the constructor of the base class and give it a parameter. This can be done in one of two ways.

Firstly, to provide a default "static" value:

  1. public SportsCar(bool roofUp):base(Color.PeachPuff)
  2. {
  3. isRoofUp = roofUp;
  4. }

Or you can add another parameter to the constructor and use this to call the base constructor.

  1. public SportsCar(bool roofUp, Color carColour): base(carColour)
  2. {
  3. isRoofUp = roofUp;
  4. }

Private Constructors

You can also mark the constructor as private, which will have the effect of not allowing the class to be instantiated. This is useful for abstract classes where you should not create an instance.

  1. private PoliceCar()
  2. {
  3. }

The following code will not compile as the program cannot "see" the private method.

  1. PoliceCarcar = new PoliceCar();

Destructors

Destructors work slightly differently in that the syntax is a shortcut to an override of the Finalize method, however, all you really need to know is that they are used to finalise the class ready for removal from memory. The Garbage Collector always calls the destructor; you never call it from within your code. Since you cannot call the destructor, you cannot overload the destructor method.

  1. ~baseCarClass ()
  2. {
  3. // Code to scrap the car (realistically this would be closing files and connections)
  4. }

This is interpreted by the compiler as:

  1. protected override void Finalize()
  2. {
  3. try
  4. {
  5. // Code to scrap the car (realistically this would be closing files and connections)
  6. }
  7. finally
  8. {
  9. base.Finalize();
  10. }
  11. }

Full Code

  1. using System;
  2. using System.Drawing;
  3.  
  4. class TestBaseCarClass
  5. {
  6. static void Main()
  7. {
  8. baseCarClass car = new baseCarClass();
  9. SportsCar sporty1 = new SportsCar(true);
  10. SportsCar sporty2 = new SportsCar(true, Color.PapayaWhip);
  11. PoliceCar copper = new PoliceCar();
  12. }
  13. }
  14.  
  15. public class baseCarClass
  16. {
  17. public bool isEngineRunning;
  18. public decimal speed;
  19. public decimal distanceTraveled;
  20. public decimal fuelLevel;
  21. public Color colour;
  22.  
  23. // Default Constructor
  24. public baseCarClass()
  25. {
  26. colour = Color.Black;
  27. }
  28.  
  29. // Custom Constructor
  30. public baseCarClass(Color carColour)
  31. {
  32. colour = carColour;
  33. }
  34.  
  35. ~baseCarClass()
  36. {
  37. // Code to scrap the car (realistically this would be closing files and connections)
  38. }
  39.  
  40. public void startEngine()
  41. {
  42. }
  43.  
  44. void accelerate()
  45. {
  46. }
  47.  
  48. void brake()
  49. {
  50. }
  51.  
  52. void stopEngine()
  53. {
  54. }
  55. }
  56.  
  57. public class SportsCar : baseCarClass
  58. {
  59. public bool isRoofUp;
  60.  
  61. public void RaiseRoof()
  62. {
  63. isRoofUp = true;
  64. }
  65.  
  66. public void DropRoof()
  67. {
  68. isRoofUp = false;
  69. }
  70.  
  71. // Constructor using base constructor with static value
  72. public SportsCar(bool roofUp): base(Color.PeachPuff)
  73. {
  74. isRoofUp = roofUp;
  75. }
  76.  
  77. // Constructor calling base constructor with a parameter
  78. public SportsCar(bool roofUp, Color carColour): base(carColour)
  79. {
  80. isRoofUp = roofUp;
  81. }
  82. }
  83.  
  84. public class PoliceCar : baseCarClass
  85. {
  86. public void Siren()
  87. {
  88. // Make some noise!
  89. }
  90.  
  91. // Private constructor means we cannot create an instance of this class
  92. private PoliceCar()
  93. {
  94. }
  95. }

Last updated on: Friday 23rd June 2017

Did you Like this Post? Why not Like us on Facebook?

 

Comments
  1. Penny Baker
    Penny Baker

    Hi Tim,

    Thanks for the tremendous effort it must have taken to put up such a detailed site! It has been a very effective learning tool for me.
    However, today I ran into a compiler problem when I tried the code on the "Constructors and Destructors" page.

    The message read:
    'testClass': member names cannot be the same as their enclosing type

    After banging around through different sites, I realized that it was complaining about the 'void' keyword in the constructors. I have VS Professional 2008, and it will not allow return types for constructors. Changing the line to read:

    static testClass()

    worked like a charm.

    Just thought I'd let you know...

    Thanks again.
    Penny Baker

Leave a Reply

Your email address will not be published.