Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    • Enhancing Performance with File Compression in Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Tuesday, May 20
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Difference Between Finalize and Dispose Method

    Difference Between Finalize and Dispose Method

    Dhanik Lal SahniBy Dhanik Lal SahniMay 2, 2018No Comments5 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Difference Between Finalize and Dispose Method
    Share
    Facebook Twitter LinkedIn Pinterest Email

    While working on real time projects, we normally create so many intefaces, clasess and using unmanged resources like DB connection, files operation etc. To manage performance of the application these resources should be freed on time. We can cleanup those resources using Dispose and Finalize methods.

    Class instances encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, we should provide both an explicit and an implicit way to free those resources.

    We should provide implicit control by implementing the protected Finalize on an object.The Finalize method is called when our object is garbage collected and we have no guarantee when this will happen (we can force it, but it will hurt performance).

    In some cases, we might want to release external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved by explicitly releases resources when they are no longer being used. To provide explicit control, we should implement the Dispose provided by the IDisposable.

    The standard practice is to implement IDisposable and Dispose so that we can use our object in a using statment. Such as using(var foo = new MyObject()) { }. And in your finalizer, you call Dispose, just in case the calling code forgot to dispose of you.

    Finalize Method

    • Finalizers should always be protected, not public or private so that the method cannot be called from the application’s code directly and at the same time, it can make a call to the base.Finalize method
    • Finalizers should release unmanaged resources only
    • The framework does not guarantee that a finalizer will execute at all on any given instance
    • Never allocate memory in finalizers or call virtual methods from finalizers
    • Avoid synchronization and raising unhandled exceptions in the finalizers
    • The execution order of finalizers is non-deterministic—in other words, you can’t rely on another object still being available within your finalizer
    • Do not define finalizers on value types
    • Don’t create empty destructors. In other words, you should never explicitly define a destructor unless your class needs to clean up unmanaged resources and if you do define one, it should do some work. If, later, you no longer need to clean up unmanaged resources in the destructor, remove it altogether.

    Dispose Method

    • Implement IDisposable on every type that has a finalizer
    • Ensure that an object is made unusable after making a call to the Dispose method. In other words, avoid using an object after the Dispose method has been called on it
    • Call Dispose on all IDisposable types once you are done with them
    • Allow Dispose to be called multiple times without raising errors
    • Suppress later calls to the finalizer from within the Dispose method using the GC.SuppressFinalize method
    • Avoid creating disposable value types
    • Avoid throwing exceptions from within Dispose methods

    Microsoft recommendation on Object Cleanup

    Microsoft recommends that you implement both Dispose and Finalize when working with unmanaged resources. The Finalize implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose method explicitly. Additionally call the Dispose method for any .NET objects that you have as components inside that class(having unmanaged resources as their member) from the Dispose method.

    Deciding Factor for Dispose/Finalized Method

    Destructor ~(it’s almost equal to base.Finalize()), The destructor is converted into an override version of the Finalize method that executes the destructor’s code and then calls the base class’s Finalize method. It is totally non deterministic and we can’t know when will be called because it depends on GC.

    • If a class contains no managed resources and no unmanaged resources, it doesn’t need to implement IDisposable or have a Finalize.
    • If the class has only managed resources, it should implement IDisposable but it doesn’t need a Finalize.
    • If the class has only unmanaged resources, it needs to implement IDisposable and needs a Finalize in case the program doesn’t call Dispose. The Dispose method must be safe to run more than once. You can achieve that by using a variable to keep track of whether it has been run before.
    • The Dispose method should free both managed and unmanaged resources.
    • The Finalize should free only unmanaged resources.
    • After freeing resources, the Dispose should call GC.SuppressFinalize, so the object can skip the finalization queue.

    An Example of a an implementation for a class with unmanaged and managed resources:

    using System;
    public class DisposableClass : IDisposable
    {
        // A name to keep track of the object.
        public string ProductName = "";
        // Free managed and unmanaged resources.
        public void Dispose()
        {
            FreeResources(true);
        }
        // Destructor to clean up unmanaged resources
        // but not managed resources.
        ~DisposableClass() // the finalizer
        {
            FreeResources(false);
        }
        // Keep track if whether resources are already freed.
        private bool IsResourcesFreed = false;
        // Free resources.
        private void FreeResources(bool freeManagedResources)
        {
            Console.WriteLine(ProductName + ": FreeResources");
            if (!ResourcesAreFreed)
            {
                // Dispose of managed resources if appropriate.
                if (freeManagedResources)
                {
                    // Dispose of managed resources here.
                    Console.WriteLine(ProductName + ": Dispose of managed resources");
                }
                // Dispose of unmanaged resources here.
                Console.WriteLine(ProductName + ": Dispose of unmanaged resources");
                // Remember that we have disposed of resources.
                IsResourcesFreed = true;
                // We don't need the destructor because
                // our resources are already freed.
                GC.SuppressFinalize(this);
            }
        }
    }
    

    Summary

    Timely Object cleanup is very important for high performing application. Use Dispose and Finalize wisely in code.

    .net
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleCohesion And Coupling – Approach for Design – Continue
    Next Article ASP.NET MVC Interview Question
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni6 Mins Read

    Top 10 Salesforce Flow Features of Salesforce Summer ’25

    May 11, 2025
    By Dhanik Lal Sahni6 Mins Read

    Unlock the Power of Vibe Coding in Salesforce

    April 30, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Dynamic Queueable Chaining in Salesforce Apex

    April 21, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) einstein (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex (3) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (140) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) einstein (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex (3) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (140) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.