Thursday, 7 July 2016

Difference between Finalize() and Dispose() - C#.NET

What is the difference between Finalize() and Dispose()?

Finalize()Dispose()
It belongs to the Object class.It belongs to the Idisposable interface.
It is slower method.It is faster method.
It is non-deterministic function, it means when Garbage Collector will call finalize() method to reclaim memory.It is deterministic function as Dispose() method is explicitly called by the User code.
It can be used to free unmanaged resources when you implement it like files, database connections etc. which is held by an object before that object is destroyed.It is used to free unmanaged resources like, files, database connections, etc. at any time.


Example for implementing Finalize method

If you want to implement Finalize method, it is recommended to use Finalize and Dispose method together as shown below:
  1. // Using Dispose and Finalize method together
  2. public class MyClass : IDisposable
  3. {
  4. private bool disposed = false;
  5. //Implement IDisposable.
  6. public void Dispose()
  7. {
  8. Dispose(true);
  9. GC.SuppressFinalize(this);
  10. }
  11.  
  12. protected virtual void Dispose(bool disposing)
  13. {
  14. if (!disposed)
  15. {
  16. if (disposing)
  17. {
  18. // TO DO: clean up managed objects
  19. }
  20. // TO DO: clean up unmanaged objects
  21. disposed = true;
  22. }
  23. }
  24. //At runtime C# destructor is automatically Converted to Finalize method
  25. ~MyClass()
  26. {
  27. Dispose(false);
  28. }
  29. }

    Example for implementing the dispose method

    1. public class MyClass : IDisposable
    2. {
    3. private bool disposed = false;
    4. //Implement IDisposable.
    5. public void Dispose()
    6. {
    7. Dispose(true);
    8. GC.SuppressFinalize(this);
    9. }
    10.  
    11. protected virtual void Dispose(bool disposing)
    12. {
    13. if (!disposed)
    14. {
    15. if (disposing)
    16. {
    17. // TO DO: clean up managed objects
    18. }
    19. // TO DO: clean up unmanaged objects
    20.  
    21. disposed = true;
    22. }
    23. }
    24. }

No comments:

Post a Comment