Thursday, 21 December 2017

What is Finalize and how to implement it in C#?

Finalize:-

The cleanup and releasing the unmanaged resources we use finalize method.

If your class is not using unmanaged resources just forget about the finalize.

We cannot call finalize method explicitly like: abc.finalize() or anything. This method is called by Garbage collector.

When garbage collector comes into picture to remove the object and release the memory consumed by the object it checks if that object has Finalize method implemented it(GC) moves that object into finalize queue.

GC comes frequently to release the generation zero bucket. But when GC would come to release the finalize queue object we do not know.

So, checking of finalize queue is very less. So, that object does not remove if it is not in use. So, object still consume CPU memory.

Now how to implement finalize?

To implement finalize we use Destructor.

When your code compiles that Destructor converts into finalize method.

See the simple Employee class with destructor rounded there in the image: -

To show Finalize method i am using Telerik JustDecomplie software. See after compilation Employee class have Finalize() method which is called by the GC itself.


No comments:

Post a Comment