- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are destructors in C# programs?
A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope.
It has exactly the same name as that of the class with a prefixed tilde (~), for example, our class name is Demo.
public Demo() { // constructor Console.WriteLine("Object is being created"); } ~Demo() { //destructor Console.WriteLine("Object is being deleted"); }
Let us see an example to learn how to work with Destructor in C#.
Example
using System; namespace LineApplication { class Line { private double length; // Length of a line public Line() { // constructor Console.WriteLine("Object is being created"); } ~Line() { //destructor Console.WriteLine("Object is being deleted"); } public void setLength( double len ) { length = len; } public double getLength() { return length; } static void Main(string[] args) { Line line = new Line(); // set line length line.setLength(6.0); Console.WriteLine("Length of line : {0}", line.getLength()); } } }
Output
Object is being created Length of line : 6 Object is being deleted
- Related Articles
- What are constructors in C# programs?
- What are the differences between constructors and destructors in C#?
- Destructors in C++
- What are System Programs?
- Playing with Destructors in C++
- What is default constructor in C# programs?
- When to use virtual destructors in C++?
- What is a parameterized constructor in C# programs?
- C/C++ Tricky Programs
- C++ Interview questions based on constructors/ Destructors
- Different Star Pattern Programs in C#
- How many destructors can we have in one class in C#?
- PHP Constructors and Destructors
- Destructors and Garbage Collection in Perl
- Memory Layout of C Programs

Advertisements