A destructor is a special method that is used to perform cleanup operations before an object is removed from memory. It is mainly used to release unmanaged resources used by an object.
In this chapter, you will learn what a destructor is, its syntax, features, and how to use it in C# with examples.
A destructor is a special method in C# that is automatically called by the Garbage Collector (GC) before an object is removed from memory. It is used to release unmanaged resources, such as file handles, database connections, network sockets, and other system resources.
A destructor has the same name as its class and is prefixed with the tilde (~) symbol. A class can have only one destructor, and it cannot be called directly from the program.
The following syntax is used to declare a destructor in C#:
In this syntax;
Let us take an example to illustrate the destructor in C#.
Output:
An instance of Tpointtech class is created. An instance of Tpointtech class is destroyed.
Explanation:
In this example, we have taken a class constructor. When we create an object of the Tpointtech class, the constructor executes and shows a message. After setting the object to null, the Garbage Collector is forced to run using GC.Collect() and GC.WaitForPendingFinalizers() functions, which invoke the destructor. After that, the destructor runs automatically to perform cleanup tasks before the object is destroyed.
Several main characteristics of the destructor in the C# programming language are as follows:
A destructor is commonly used to release unmanaged resources, such as files, database connections, or network resources.
In this example, a file is opened in the constructor and automatically closed in the destructor when the object is destroyed by the Garbage Collector.
Output:
File opened successfully. Working with file... File closed successfully.
Explanation:
In this example, we have created a class called File_hand, and its constructor opens a file when the object is created. The destructor ensures that the file is closed successfully when the Garbage Collector destroys the object. It ensures safe resource management by automatically releasing the file handle when it is no longer required.
C# uses a non-deterministic garbage collection system, which means that we can't predict exactly when the garbage collector will execute or when the destructor will be invoked. The runtime decides when it's a good time to cleanup memory based on available resources and memory pressure.
In C# programming, a destructor should be utilized when a class performs several tasks with unmanaged resources, such as database connections, network sockets, file handling, and many others. The main use of a destructor is to act as a cleanup mechanism to ensure that unmanaged resources are properly released before the object is destroyed.
C# destructors can also serve as a backup safety net if the Dispose() method is not explicitly invoked. Moreover, destructors are also useful when we deal with unmanaged resources, and the IDisposable interface with the Dispose() method is suitable for cleanup resources. If we are working with interop code that interacts with native libraries or APIs, it is very beneficial.
The IDisposable interface and the Dispose pattern provide a controlled way to release resources as soon as they are no longer needed. In this example, a file is opened, processed, and automatically closed by calling the Dispose() method through the using statement.
This example demonstrates how to implement the IDisposable interface and the Dispose pattern to release file resources immediately after they are no longer needed. The using statement automatically calls the Dispose() method, ensuring proper resource cleanup.
Output:
File Opened Working with file File Closed
Explanation:
In this example, we have taken the file_handle class that opens a file in its constructor and ensures cleanup through the Dispose() method, which is automatically invoked at the end of the using block. After that, the Dispose(bool disposing) method releases both managed and unmanaged resources, while the destructor behaves as a safety net if the Dispose() method is not explicitly called.
In the C# programming language, both destructors and the Finalize() method are mainly utilized for resource cleanup, but they differ in several aspects. A destructor in C# is essentially a syntax wrapper around the Finalize() method provided by the .NET runtime. If we write a destructor in C#, the compiler automatically translates it into an override of the Object.Finalize() method. We can override the Finalize() manually, but defining a destructor is the simpler and safer option.
It has the following syntax:
Let us take an example to illustrate the destructor and finalize method in C#.
Output:
main.cs(10,29): error CS0249: Do not override `object.Finalize()'. Use destructor syntax instead
Explanation:
In this example, we have taken the class Tpoint, and then take a constructor that creates an object, while the Finalize() method is automatically called by the garbage collector to cleanup resources before object destruction. Finally, the program ensures that the Finalize() method executes before the main method ends by forcing garbage collection using GC.Collect() and GC.WaitForPendingFinalizers() methods.
There are several differences between a constructor and a destructor in C#. Some of them are as follows:
| Features | Constructors | Destructors |
|---|---|---|
| Purpose | It initializes the object upon creation. | It performs the cleanup operations before destroying the object. |
| Invocation | It is explicitly invoked during the object creation. | It is automatically invoked by the Garbage Collector when the object is destroyed. |
| Resource Allocation | It is utilized for resource allocation. | It is often utilized for resource deallocation. |
| Parametrization | It can accept parameters for custom initialization. | It doesn't allow any parameters. |
| Instances | Several constructors can be defined with different parameters. | A class contains only one destructor and doesn't contain any overloads. |
We request you to subscribe our newsletter for upcoming updates.