Destructors are used to destruct instances of classes.
Following are some key points about C# Destructor:
- Destructor in a class must be prefix with the tilde "~" character.
Ex. If your class name is "MyClass" then it's destructor name should be "~MyClass()
Sample Program:public class MyClass{public MyClass(){Console.WriteLine("Constructor");}~MyClass(){Console.WriteLine("Destructor");}} - A Class can only have one destructor.
- Destructors can not defined in structs.
- Destructors can not be overloaded or inherited.
- Destructors can not be called. They invoked automatically.
- Destructors does not take modifiers or any parameters.
- Use destructor only when your class consumes 'unmanaged' resources like files, GDI objects (Bitmap),SQL connection objects.
- The destructor implicitly calls 'Finalize' method of the base class object.
- Empty destructor should not be used.When a class has destructor, an entry is added in "Finalize" queue. Empty destructor causes loss of performance.
- The programmer has no control over when the destructor is called because this is determined by the garbage collector.
Destructors are not useful in most of the cases. You need to be careful if you are adding destructor in your classes.
To release resources immediately, you can also choose to implement the dispose pattern and the IDisposable interface. The IDisposable.Dispose implementation can be called by consumers of your class to free unmanaged resources, and you can use the Finalize method to free unmanaged resources in the event that the Dispose method is not called.
I hope this article will help you in understanding C# Destructors.
Thanks & Regards,
Mahesh Bagul