TagDispose method

Finalize method or Destructor

Finalize method or Destructor are synonyms. We create destructor by typing ~ (tilde sign) and class name. Use of destructor is to cleanup unamaged resources when Garbage collector runs. It is a good practice that your destructor calls Dispose method and provides it with false boolean value. Why with false value? Because First Dispose method is called by your code and provides second Dispose method with true value, meaning only managed code will be disposed of, and by providing Dispose of method with false method we ensure that garbage collector will not try to destroy of already disposed of objects.

Destructor can be called in two ways:

  1. When Garbage collector runs by itself
  2. When we invoke Garbage Collector by using GC.Collect()

Implementing IDisposable

As we saw in previous post, we can use using statement to automatically dispose of objects. To use using directive our class needs to implement IDisposable interface.  To correctly implement IDisposable interface we should stick to some guidelines. Following example will show you the correct way to implement it.

Example of Implementing IDisposable interface to a class

We will start by creating FileRead class whose job is to create file and write line to it. FileRead class will implement IDispose interface and two Dispose methods. General rule is that you should create two Dispose methods:

  • public void method with no parameters
  • protected void method with a boolean input parameter

Job of public Dispose method is to call second Dispose method where objects are really disposed of, and second job is to notify Garbage collector that this instance of class is cleaned up and that there is no need to check-up upon it during garbage collection.

More examples of IDisposable coming up soon.

© 2021 LearnC#WithDarko

Theme by Anders NorenUp ↑