Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • How to Confidently Manage Transactions in Salesforce Apex
    • Building a Dynamic Tree Grid in Lightning Web Component
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Saturday, August 2
    • Home
    • Salesforce Platform
      • Architecture
      • Apex
      • Lightning Web Components
      • Integration
      • Flows & Automation
      • Best Practices
      • Questions
      • News
      • Books Testimonial
    • Industries
      • Artificial Intelligence
    • Hire Me
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Downloads
      • Salesforce Release Notes
      • Apex Coding Guidelines
    • About Us
      • Privacy Policy
    • Contact Us
    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

    How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI

    July 28, 2025
    By Dhanik Lal Sahni7 Mins Read

    Top Mistakes Developers Make in Salesforce Apex Triggers

    July 25, 2025
    By Dhanik Lal Sahni14 Mins Read

    The Ultimate Guide to Apex Order of Execution for Developers

    July 20, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Ranked #1 Salesforce Developer Blog by SalesforceBen.com
    SFBenTopDeveloper
    Ranked #4 Salesforce Developer Blog by ApexHours.com
    ApexHoursTopDevelopers
    Categories
    Archives
    Tags
    apex (116) apex best practices (5) apex code best practice (10) apex code optimization (6) Apex logging (4) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (23) salesforce (150) salesforce apex (52) salesforce api integration (5) Salesforce Interview Question (5) 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

    MailChimp

    Expert Salesforce Developer and Architect
    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 10 Salesforce CRM Trends to Watch in 2025 July 18, 2025
    • Discover the Top 10 Salesforce AppExchange Apps to Boost Productivity July 10, 2025
    • Top 20 Salesforce Data Cloud Interview Questions & Answers for Admins June 5, 2025
    • 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
    Archives
    Categories
    Tags
    apex (116) apex best practices (5) apex code best practice (10) apex code optimization (6) Apex logging (4) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (23) salesforce (150) salesforce apex (52) salesforce api integration (5) Salesforce Interview Question (5) 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.