TechCognition

Microsoft Visual Studio 2017 Promo Code
Microsoft Office 2016 Promo Code

Finalizers or Destructor usage - C# Coding Standard 10

Avoid using destructor in C# because of service performance penalty due to the Garbage Collector (GC) works. Another reason to avoid destructor is, we can not predict when destructor will get called to clean up the resources. C# destructors are not really destructors like in C++, they are just C# compiler feature to represent CLR Finalizers. Follow the below usage guidelines if you want to  use destructors in C# definetly.

             If you want use destructor, call GC.SuppressFinalize() inside destructor so that it removes the object quickly from memory.

 

             If your class is using unmanaged or expensive resources like database connections, Windows handles, or graphics which needs to be disposed as soon as possible, implements IDisposal interface which allows us to release resources explicitly. If we implements IDisposable interface, we need to implements Dispose() method which is member of IDisposable interface.

 

             If base class is implementing IDisposable interface, child class which is implementing base class shouldn't implement IDisposable interface instead it should implement Dispose() method of base class.

 

             Don't access any reference type members in the destructor because it is very much possible that all those reference members already garbage collected before destructor called by GC. In this scenario, if we try to dereferencing those objects may throw exceptions.

 

             We can access value type members in the destructor.

 

             You should not throw exceptions inside destructor.

 

 

Add comment

Loading

© Copyright 2018 www.techcognition.com | Sitemap