C# Destructor – How to use

destructors
In this chapter you will learn

  • What is Destructor in C#?
  • What is the use of Destructor in Program?
  • How to use it in Program?

What is Destructor (~)?

Destructors are the techniques to remove instances of classes as soon as class closed. It is very useful techniques to clean memory and remove all the instances of program. Using of destructors you can release memory if your program is using expensive external resource as files, image etc.

Note: You should not use empty destructor in program. When you use destructor, an entry is created in Finalize queue. Therefore, when destructor is called, the garbage collector in invoked to process the queue. If you have used empty destructor, it cause unnecessary system performance issue.

When a Destructor called it automatically invokes Finalize Method. Finalize method in C# is used for cleaning memory from unused objects and instances. So, when you call destructor, it actually translates into following code.






  • The programmer has no control when destructor will be executed because it is defined by garbage collector. Garbage collector automatically checks for objects that is no longer referenced or no longer being used by application. When garbage collector found such objects, it removes them automatically and free up memory.

    In actually, C# doesn’t require explicit memory management because the .Net Framework garbage collector automatically does it for you.

    Programming Example

    Summary

    In this chapter you have learned what destructor is in c # and how to use it for cleaning memory from unused objects and instances. In the next chapter you will learn about Constructor Overloading.


    Leave a Reply

    Your email address will not be published. Required fields are marked *