Friday, August 29, 2014

C# Destructors


Destructors are used to destruct instances of classes.

Following are some key points about C# Destructor:

  1. 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");
            }
        }
  2. A Class can only have one destructor.
  3. Destructors can not defined in structs. 
  4. Destructors can not be overloaded or inherited.
  5. Destructors can not be called. They invoked automatically.
  6. Destructors does not take modifiers or any parameters.
  7. Use destructor only when your class consumes 'unmanaged' resources like files, GDI objects (Bitmap),SQL connection objects.
  8. The destructor implicitly calls 'Finalize' method of the base class object.
  9. Empty destructor should not be used.When a class has destructor, an entry is added in "Finalize" queue. Empty destructor causes loss of performance.
  10. The programmer has no control over when the destructor is called because this is determined by the garbage collector.
Conclusion:

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







No comments:

Post a Comment