277

Why do some people use the Finalize method over the Dispose method?

In what situations would you use the Finalize method over the Dispose method and vice versa?

1

16 Answers 16

183

The finalizer method is called when your object is garbage collected and you have no guarantee when this will happen (you can force it, but it will hurt performance).

The Dispose method on the other hand is meant to be called by the code that created your class so that you can clean up and release any resources you have acquired (unmanaged data, database connections, file handles, etc) the moment the code is done with your object.

The standard practice is to implement IDisposable and Dispose so that you can use your 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.

5
  • 31
    You need to be a bit careful about calling Dispose from your Finalize implementation -- Dispose may also dispose managed resources, which you don't want to touch from your finalizer, as they may already have been finalized themselves.
    – itowlson
    Apr 9, 2009 at 5:11
  • 7
    @itowlson: Checking for null combined with the assumption that objects can be disposed of twice (with second call doing nothing) should be good enough.
    – Samuel
    Apr 9, 2009 at 5:16
  • 7
    The standard IDisposal pattern and the hidden implementation of a Dispose(bool) to handle disposing managed components optional seems to cater for that issue.
    – Brody
    Apr 9, 2009 at 5:34
  • It sounds like there is no reason to implement the destructor (the ~MyClass () method) and rather always implement and call the Dispose() method. Or am I wrong? Could someone give me an example when both should be implemented?
    – dpelisek
    Apr 30, 2019 at 12:35
  • @dpelisek You implement the destructor as a safety measure, to guarantee that unmanaged resources are always released. If you are 100% certain that Dispose() will always be called, then you are correct, there's no need for a finalizer. But it's a best practice to implement both. Feb 23, 2021 at 17:49
136

Others have already covered the difference between Dispose and Finalize (btw the Finalize method is still called a destructor in the language specification), so I'll just add a little about the scenarios where the Finalize method comes in handy.

Some types encapsulate disposable resources in a manner where it is easy to use and dispose of them in a single action. The general usage is often like this: open, read or write, close (Dispose). It fits very well with the using construct.

Others are a bit more difficult. WaitEventHandles for instances are not used like this as they are used to signal from one thread to another. The question then becomes who should call Dispose on these? As a safeguard types like these implement a Finalize method, which makes sure resources are disposed when the instance is no longer referenced by the application.

6
  • 74
    I could not understand this approved answer. I still want to know the different. What it is?
    – Ismael
    Dec 13, 2012 at 19:23
  • 30
    @Ismael: The biggest situation where Finalize may be justified is when there are a number of objects which are interested in having a resource kept alive, but there's no means by which an object that ceases to be interested in the resource can find out if it's the last one. In such case, Finalize will usually only fire when nobody's interested in the object. The loose timing of Finalize is horrible for non-fungible resources such as files and locks, but may be okay for fungible resources.
    – supercat
    May 17, 2013 at 20:56
  • 16
    +1 to supercat for a great new (to me) word. The context made it pretty clear, but just in case for the rest of us, here's what wikipedia says: "Fungibility is the property of a good or a commodity whose individual units are capable of mutual substitution, such as sweet crude oil, shares in a company, bonds, precious metals, or currencies."
    – Jon Coombs
    Oct 23, 2013 at 7:57
  • 6
    @JonCoombs: That's pretty much right, though it may be worth noting that the term "fungible resource" is applied to things which are freely substitutable until they are acquired and become freely substitutable again after release or abandonment. If the system has a pool of lock objects and code acquires one which it associates with some entity, then as long as anyone is holding that a reference to that lock for the purpose of associating it with that entity, that lock may not be substituted with any other. If all code that cares about the guarded entity abandons the lock, however,...
    – supercat
    Aug 13, 2015 at 18:09
  • ...then it would again become freely substitutable until such time as it is associated with some other entity.
    – supercat
    Aug 13, 2015 at 18:10
83

Finalize is the backstop method, called by the garbage collector when it reclaims an object. Dispose is the "deterministic cleanup" method, called by applications to release valuable native resources (window handles, database connections, etc.) when they are no longer needed, rather than leaving them held indefinitely until the GC gets round to the object.

As the user of an object, you always use Dispose. Finalize is for the GC.

As the implementer of a class, if you hold managed resources that ought to be disposed, you implement Dispose. If you hold native resources, you implement both Dispose and Finalize, and both call a common method that releases the native resources. These idioms are typically combined through a private Dispose(bool disposing) method, which Dispose calls with true, and Finalize calls with false. This method always frees native resources, then checks the disposing parameter, and if it is true it disposes managed resources and calls GC.SuppressFinalize.

6
  • 3
    The original recommended pattern for classes which held a mix of self-cleaning ("managed") and non-self-cleaning ("unmanaged") resources has long been obsolescent. A better pattern is to separately wrap every unmanaged resource into its own managed object which doesn't hold any strong references to anything which isn't necessary for its cleanup. Everything to which a finalizable object holds a direct or indirect strong reference will have its GC lifetime extended. Encapsulating the things that are needed for cleanup will let one avoid extending the GC lifetime of things that aren't.
    – supercat
    May 17, 2013 at 21:01
  • 2
    @JCoombs: Dispose is good, and implementing it correctly is generally easy. Finalize is evil, and implementing it correctly is generally hard. Among other things, because the GC will ensure that no object's identity will ever get "recycled" as long as any reference to that object exists, it's easy to cleaning up a bunch of Disposable objects, some of which may have already been cleaned up, is no problem; any reference to an object on which Dispose has already been called will remain a reference to an object upon which Dispose has already been called.
    – supercat
    Oct 23, 2013 at 15:49
  • 2
    @JCoombs: Unmanaged resources, by contrast, generally have no such guarantee. If object Fred owns file handle #42 and closes it, the system might attach that same number to some the file handle which is given to some other entity. In that case, file handle #42 would not refer to Fred's closed file, but to the file that was in active use by that other entity; for Fred to try to close handle #42 again would be disastrous. Trying to 100% reliably keep track of whether one unmanaged object has yet been released is workable. Trying to keep track of multiple objects is much harder.
    – supercat
    Oct 23, 2013 at 15:55
  • 2
    @JCoombs: If every unmanaged resource is placed in its own wrapper object which does nothing but control its lifetime, then outside code which doesn't know whether the resource has been released, but knows that it should be if it hasn't been already, can safely ask the wrapper object to release it; the wrapper object will know if it has done so and can carry out or ignore the request. The fact that the GC guarantees that a reference to the wrapper will always be a valid reference to the wrapper is a very useful guarantee.
    – supercat
    Oct 23, 2013 at 15:59
61

Finalize gets called by the GC when this object is no longer in use.

Dispose is just a normal method which the user of this class can call to release any resources.

If user forgot to call Dispose and if the class have Finalize implemented then GC will make sure it gets called.

2
  • 8
    Cleanest answer ever Jun 21, 2018 at 9:18
  • This should be written in official documentation Nov 11, 2021 at 13:52
44

Finalize

  • 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

  • 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

Dispose/Finalized Pattern

  • 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.
  • Cleanup the unmanaged resources in the Finalize method as well as Dispose method. 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.
3
  • 29
    I read this same answer everywhere and still i cannot understand what is the purpose of each one. I only read rules after rules, nothing more.
    – Ismael
    Dec 13, 2012 at 19:29
  • @Ismael: and also author doesnt add anything except for copying and pasting some text from MSDN.
    – Tarik
    Dec 24, 2015 at 16:14
  • @tarik I have already learnt it. I did have "promise" conception that time i asked this.
    – Ismael
    Dec 24, 2015 at 21:43
30

There're some keys about from the book MCSD Certification Toolkit (exam 70-483) pag 193:

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. Then its totally non deterministic you can't able to know when will be called because depends on GC.

If a class contains no managed resources and no unmanaged resources, it shouldn't implement IDisposable or have a destructor.

If the class has only managed resources, it should implement IDisposable but it shouldn't have a destructor. (When the destructor executes, you can’t be sure managed objects still exist, so you can’t call their Dispose() methods anyway.)

If the class has only unmanaged resources, it needs to implement IDisposable and needs a destructor in case the program doesn’t call Dispose().

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.

Dispose() should free both managed and unmanaged resources.

The destructor should free only unmanaged resources. When the destructor executes, you can’t be sure managed objects still exist, so you can’t call their Dispose methods anyway. This is obtained by using the canonical protected void Dispose(bool disposing) pattern, where only managed resources are freed (disposed) when disposing == true.

After freeing resources, 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;

class DisposableClass : IDisposable
{
    // A name to keep track of the object.
    public string Name = "";

    // Free managed and unmanaged resources.
    public void Dispose()
    {
        FreeResources(true);

        // We don't need the destructor because
        // our resources are already freed.
        GC.SuppressFinalize(this);
    }

    // Destructor to clean up unmanaged resources
    // but not managed resources.
    ~DisposableClass()
    {
        FreeResources(false);
    }

    // Keep track if whether resources are already freed.
    private bool ResourcesAreFreed = false;

    // Free resources.
    private void FreeResources(bool freeManagedResources)
    {
        Console.WriteLine(Name + ": FreeResources");
        if (!ResourcesAreFreed)
        {
            // Dispose of managed resources if appropriate.
            if (freeManagedResources)
            {
                // Dispose of managed resources here.
                Console.WriteLine(Name + ": Dispose of managed resources");
            }

            // Dispose of unmanaged resources here.
            Console.WriteLine(Name + ": Dispose of unmanaged resources");

            // Remember that we have disposed of resources.
            ResourcesAreFreed = true;
        }
    }
}
1
  • 2
    This is a nice answer! But I think this is wrong: "the destructor should call GC.SuppressFinalize". Instead, shouldn't the public Dispose() method call GC.SuppressFinalize? See: learn.microsoft.com/en-us/dotnet/api/… Calling this method prevents the garbage collector from calling Object.Finalize (which is overridden by the destructor).
    – Ewa
    Feb 25, 2019 at 16:26
9

99% of the time, you should not have to worry about either. :) But, if your objects hold references to non-managed resources (window handles, file handles, for example), you need to provide a way for your managed object to release those resources. Finalize gives implicit control over releasing resources. It is called by the garbage collector. Dispose is a way to give explicit control over a release of resources and can be called directly.

There is much much more to learn about the subject of Garbage Collection, but that's a start.

5
  • 5
    I'm pretty sure more than 1% of C# applications use databases: where you have to worry about IDisposable SQL stuff.
    – Samuel
    Apr 9, 2009 at 5:14
  • 1
    Also, you should implement IDisposable if you encapsulate IDisposables. Which probably covers the other 1%. Apr 9, 2009 at 5:16
  • @Samuel: I don't see what databases has to do with it. If you are talking about closing connections, that's fine, but that's a different matter. You don't have to dispose objects to close connections in a timely manner.
    – JP Alioto
    Apr 9, 2009 at 5:35
  • 1
    @JP: But the Using(...) pattern makes it so much simpler to cope with.
    – Brody
    Apr 9, 2009 at 5:38
  • 3
    Agreed, but that's exactly the point. The using pattern hides the call to Dispose for you.
    – JP Alioto
    Apr 9, 2009 at 6:05
6

The finalizer is for implicit cleanup - you should use this whenever a class manages resources that absolutely must be cleaned up as otherwise you would leak handles / memory etc...

Correctly implementing a finalizer is notoriously difficult and should be avoided wherever possible - the SafeHandle class (avaialble in .Net v2.0 and above) now means that you very rarely (if ever) need to implement a finalizer any more.

The IDisposable interface is for explicit cleanup and is much more commonly used - you should use this to allow users to explicitly release or cleanup resources whenever they have finished using an object.

Note that if you have a finalizer then you should also implement the IDisposable interface to allow users to explicitly release those resources sooner than they would be if the object was garbage collected.

See DG Update: Dispose, Finalization, and Resource Management for what I consider to be the best and most complete set of recommendations on finalizers and IDisposable.

4

The main difference between Dispose and Finalize is that:

Dispose is usually called by your code. The resources are freed instantly when you call it. People forget to call the method, so using() {} statement is invented. When your program finishes the execution of the code inside the {}, it will call Dispose method automatically.

Finalize is not called by your code. It is mean to be called by the Garbage Collector (GC). That means the resource might be freed anytime in future whenever GC decides to do so. When GC does its work, it will go through many Finalize methods. If you have heavy logic in this, it will make the process slow. It may cause performance issues for your program. So be careful about what you put in there.

I personally would write most of the destruction logic in Dispose. Hopefully, this clears up the confusion.

3

Diff between Finalize and Dispose methods in C#.

GC calls the finalize method to reclaim the unmanaged resources(such as file operarion, windows api, network connection, database connection) but time is not fixed when GC would call it. It is called implicitly by GC it means we do not have low level control on it.

Dispose Method: We have low level control on it as we call it from the code. we can reclaim the unmanaged resources whenever we feel it is not usable.We can achieve this by implementing IDisposal pattern.

3

The summary is -

  • You write a finalizer for your class if it has reference to unmanaged resources and you want to make sure that those unmanaged resources are released when an instance of that class is garbage collected automatically. Note that you can't call the Finalizer of an object explicitly - it's called automatically by the garbage collector as and when it deems necessary.
  • On the other hand, you implement the IDisposable interface(and consequently define the Dispose() method as a result for your class) when your class has reference to unmanaged resources, but you don't want to wait for the garbage collector to kick in (which can be anytime - not in control of the programmer) and want to release those resources as soon as you are done. Thus, you can explicitly release unmanaged resources by calling an object's Dispose() method.

Also, another difference is - in the Dispose() implementation, you should release managed resources as well, whereas that should not be done in the Finalizer. This is because it's very likely that the managed resources referenced by the object have already been cleaned up before it's ready to be finalized.

For a class that uses unmanaged resources, the best practice is to define both - the Dispose() method and the Finalizer - to be used as a fallback in case a developer forgets to explicitly dispose off the object. Both can use a shared method to clean up managed and unmanaged resources :-

class ClassWithDisposeAndFinalize : IDisposable
{
    // Used to determine if Dispose() has already been called, so that the finalizer
    // knows if it needs to clean up unmanaged resources.
     private bool disposed = false;

     public void Dispose()
     {
       // Call our shared helper method.
       // Specifying "true" signifies that the object user triggered the cleanup.
          CleanUp(true);

       // Now suppress finalization to make sure that the Finalize method 
       // doesn't attempt to clean up unmanaged resources.
          GC.SuppressFinalize(this);
     }
     private void CleanUp(bool disposing)
     {
        // Be sure we have not already been disposed!
        if (!this.disposed)
        {
             // If disposing equals true i.e. if disposed explicitly, dispose all 
             // managed resources.
            if (disposing)
            {
             // Dispose managed resources.
            }
             // Clean up unmanaged resources here.
        }
        disposed = true;
      }

      // the below is called the destructor or Finalizer
     ~ClassWithDisposeAndFinalize()
     {
        // Call our shared helper method.
        // Specifying "false" signifies that the GC triggered the cleanup.
        CleanUp(false);
     }
2

The best example which i know.

 public abstract class DisposableType: IDisposable
  {
    bool disposed = false;

    ~DisposableType()
    {
      if (!disposed) 
      {
        disposed = true;
        Dispose(false);
      }
    }

    public void Dispose()
    {
      if (!disposed) 
      {
        disposed = true;
        Dispose(true);
        GC.SuppressFinalize(this);
      }
    }

    public void Close()
    {
      Dispose();
    }

    protected virtual void Dispose(bool disposing)
    {
      if (disposing) 
      {
        // managed objects
      }
      // unmanaged objects and resources
    }
  }
1

Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object. In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive.

Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.

1

I searched the answer to this question a lot today. I will share my learnings here. My answer is based on this link, because it has the clearest explanation I have seen.

When your objects has access to unmanaged resources, you have to manually release those resources. This can be done via IDisposable or finalizer meaning they both release unmanaged resources.

Rule of thumb: Implement IDisposable to release unmanaged resources and caller code must call Dispose method. If caller forgets to call Dispose() method, you still can provide a method to release those unmanaged resources. First option is using safe handle to wrap unmanaged resource. Second option is defining a finalizer. Using safe handle is recommended way in this case.

I think this link is the clearest answer to this question. I do not know why people provide complex explanations to this question on the internet. It made me feel confused until I find that link.

-2

As we know dispose and finalize both are used to free unmanaged resources.. but the difference is finalize uses two cycle to free the resources , where as dispose uses one cycle..

2
  • Dispose frees the resource immediately. Finalize may or may not free the resource with any degree of timeliness.
    – supercat
    Dec 8, 2015 at 18:53
  • 2
    Ah, he likely means this "a finalizable object needs to be detected by the GC twice before its memory is reclaimed", read up more here: ericlippert.com/2015/05/18/…
    – aeroson
    Feb 21, 2017 at 21:12
-4

To answer on the first part you should provide examples where people use different approach for the exact same class-object. Otherwise it is difficult (or even strange) to answer.

As for the second question better read first this Proper use of the IDisposable interface which claims that

It's your choice! But choose Dispose.

In other words: The GC only knows about finalizer (if any. Also known as destructor to Microsoft). A good code will attempt to cleanup from both (finalizer and Dispose).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.