Santosh Kumar Singh
C# - Difference between Dispose and Finalize Method in C# with Example

Dispose() Method

  1. - This dispose method will be used to free unmanaged resources like files, database connection etc.
  2. - To clear unmanaged resources we need to write code manually to raise dispose() method.
  3. - This Dispose() method belongs to IDisposable interface.
  4. - If we need to implement this method for any custom classes we need to inherit the class from IDisposable interface.
  5. - It will not show any effect on performance of website and we can use this method whenever we want to free objects immediately.

Example

//Implement Dispose Method.
public class TestDispose : IDisposable
{
private bool disposed = false;

//Implement IDisposable.
public void Dispose()
{
Dispose(true);
}

protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// clean unmanged objects
}
// clean unmanaged objects).

disposed = true;
}
}
}

Finalize() Method

  1. - This method also free unmanaged resources like database connections, files etc
  2. - It is automatically raised by garbage collection mechanism whenever the object goes out of scope.
  3. - This method belongs to object class.
  4. - We need to implement this method whenever we have unmanaged resources in our code and make sure these resources will be freed when garbage collection process done.
  5. - It will show effect on performance of website and it will not suitable to free objects immediately.

Example

// Implementing Finalize method
public class Sample
{
//At runtime destructor automatically Converted to Finalize method.
~Sample()
{
// your clean up code
}
}

By Santosh Kumar Singh in .NET on Oct 07 2019
  • Pranam Bhat
    May, 2021 28

    Check here : https://techdifferences.com/difference-between-dispose-and-finalize-in-c-sharp.html

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS