What is the difference between dispose() and finalize()?

0 votes
149 views
Apollonia Nealey asked 15-Nov-2017 in programming by Apollonia Nealey

What is the difference between dispose() and finalize()?

1 Answer

0 votes
Arti Mishra answered 25-Aug-2018 by Arti Mishra
The difference between dispose() and finalize():
Generally finalize() and dispose() method is used for releasing the unmanaged resources like files, database connections, etc. But the main difference is that dispose() method is invoked(called) by the user and finalize( ) method is invoked(called) by the garbage collector before the object is destroyed. dispose( ) method is declared as public, but finalize( ) method is declared as private and at the runtime when the destructor is called it  automatically Converted to Finalize method .

Example of dispose() method

public class Test : IDisposable
{
private bool disposed = false;
// dispose method declare
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// clean the managed objects
}
// clean the unmanaged objects
disposed = true;
}
}
}
Example of finalize() method

public class Test : IDisposable
{
private bool disposed = false;
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// clean the managed objects
}
// clean the unmanaged objects
disposed = true;
}
}
//At runtime C# destructor is automatically Converted to Finalize method
~Test()
{
Dispose(false);
}
}