Constructor and Destructor in C#

Learn via video courses
Topics Covered

Overview

Constructor and Destructor in C# are essential elements of object-oriented programming. Constructors are special methods within a class responsible for initializing objects when they're created. They share the class's name, have no return type, and handle tasks like setting initial states or overloading for diverse object creation options. On the other hand, destructors, also known as finalizers, come into play when an object is no longer needed,ensuring proper resource cleanup and memory management in C# applications.

Introduction

In C#, constructors are special methods used exclusively to initialize objects when they are created. They share the class's name, possess no return type (not even void), and their primary purpose is to set up instance variables or properties. This feature enables the overloading of constructors, allowing for the creation of multiple constructors within a class, each accepting different parameters. Destructors, also referred to as finalizers in C#, are responsible for resource cleanup before an object undergoes destruction or garbage collection. Noted by a tilde (~) followed by the class name, explicit destructor implementation is seldom necessary thanks to the automatic memory management facilitated by C#'s garbage collector.

What is Constructor in C#

A constructor in C# is a special method within a class that is automatically called when an object of that class is created. Constructors are used to initialize the state or set up the initial conditions of an object. They have the same name as the class and do not have a return type, not even void.

Example:

Output:

  • We have a Person class with two private fields: name and age.
  • The Person class has a constructor that sets the name and age fields when a Person object is created.
  • There's a DisplayInfo method to display the person's name and age.
  • In the Main method, we create a Person object with the constructor, providing values for name and age.
  • We call DisplayInfo to show the person's information.

Features of Constructor

Constructors in C# have several features and characteristics that make them a fundamental part of object-oriented programming. Here are the key features of constructors:

  • Initialization:

    Constructors are primarily used for initializing the state of objects. They set the initial values of fields, properties, and other members of an object to ensure that it starts in a valid state.

  • Automatic Invocation:

    Constructors are automatically called when an object is created using the new keyword. This ensures that the object is properly initialized before it is used.

  • Same Name as Class:

    Constructors have the same name as the class they belong to. This naming convention makes it clear which constructor should be called when creating objects.

  • Initialization Order:

    Constructors in a class hierarchy are called in a specific order, starting with the base class constructor and then proceeding to derived class constructors. This ensures that the object's base class is initialized before the derived class.

  • Parameterization:

    Constructors can accept parameters, allowing you to customize object initialization based on the values provided during object creation. This feature enables constructor overloading, where multiple constructors with different parameters can be defined.

Types of C# Constructor

Default Constructor

This is a constructor with no parameters. If you don't define any constructors in your class, C# provides a default parameterless constructor automatically. It initializes fields and properties to their default values (e.g., null for reference types, 0 for numeric types).

Example:

Output:

Parameterized Constructor

A constructor that accepts one or more parameters, allowing you to initialize object properties with specific values when an object is created.

Example:

Output

Copy Constructor

While C# doesn't have a built-in copy constructor like some other programming languages, you can create one yourself. A copy constructor initializes a new object with the values of an existing object of the same type. It's often used for creating deep copies of objects.

Example:

Output:

Private Constructor

A constructor can be marked as private, making it inaccessible from outside the class. This is commonly used in design patterns like the Singleton pattern, where you want to ensure that only one instance of a class is created.

Example:

Output:

Static Constructor

A static constructor is used to initialize static members of a class. It's called automatically before any static members are accessed or any static methods are called within the class. Static constructors are defined using the static keyword.

Example:

Output:

What is Destructor in C#?

In C#, a destructor is a special method that is used to clean up resources and perform any necessary finalization tasks for an object before it is destroyed. Destructors are defined in a class using the ~symbol followed by the class name. They are the opposite of constructors, which are used for initializing objects.

Example:

Output:

  • When you create an instance of the MyClass class using MyClass obj = new MyClass();, the constructor is called, and it prints "Constructor called" to the console.
  • At the end of the Main method, when the obj object goes out of scope, it becomes eligible for destruction. The Garbage Collector automatically calls the destructor, and it prints "Destructor called" to the console.
  • You'll see "Constructor called" first, indicating the object creation, and then "Destructor called," indicating the object's destruction when the program ends.

Features of Destructor

  • Automatic Invocation:

    Destructors are automatically invoked by the .NET Garbage Collector when an object is no longer in use and is being reclaimed by memory management.

  • Resource Cleanup:

    Destructors are often used for resource cleanup, such as releasing unmanaged resources like file handles, network connections, or other external resources. This helps prevent resource leaks.

  • No Explicit Calling:

    You cannot explicitly call a destructor on an object. They are called automatically when the object is eligible for garbage collection.

  • Non-Deterministic:

    The exact timing of when a destructor is called is non-deterministic and controlled by the Garbage Collector, which means you can't predict precisely when it will run.

  • Limited Use:

    While destructors are useful for managing resources, it's often recommended to use other mechanisms, such as the using statement for resource cleanup or implementing the IDisposable interface for more controlled and predictable resource management.

Difference between Constructor and Destructor

Here's a tabular representation of the differences between constructor and destructor in C#:

AspectConstructorDestructor
PurposeInitializes object upon creationPerforms cleanup before destruction
SyntaxDefined using the class nameDefined using the ~ symbol and the class name
InvocationExplicitly called during object creationAutomatically called by Garbage Collector when the object is destroyed
Number of InstancesMultiple constructors can be defined with different parametersOnly one destructor per class, no overloads
ParameterizationCan accept parameters for custom initializationNo parameters are allowed
Multiple DefinitionsMultiple constructors allowed with different signaturesOnly one destructor per class, no overloads
Resource AllocationTypically used for resource allocationOften used for resource deallocation
Timing of ExecutionControlled by object creationNon-deterministic, controlled by Garbage Collector
Base Class InheritanceBase class constructors called firstDerived class destructors called first in inheritance chain
Controlled Resource ReleaseRarely used for controlled resource releaseOften used to release unmanaged resources

Conclusion

  • Constructors set initial object states, while destructors clean up before object destruction, mainly for resource release.
  • Constructors customize object creation, allowing variations. Destructors, just one per class, handle cleanup before destruction, no parameters allowed.
  • Constructors set up objects on creation, while destructors run automatically when objects are no longer referenced.
  • Constructors allocate and set up resources, both managed and unmanaged. Destructors release resources, especially unmanaged ones like file handles or database connections.
  • Constructors are executed when an object is created, determining its initial state. Destructors run non-deterministically during garbage collection when the object is unused.