I confess that I still do not understand everything about manipulating the destruction of an object in C # and now, when testing Visual Studio 2015 Preview , when implementing a class I have included the inheritance of IDisposable
and I used the Implement interface with Dispose pattern option.
Then the following code was included in my class:
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a
// finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code
// to free unmanaged resources.
// ~DBConnection() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
I could not understand these comments with TODOs on the finalizer ~DBConnection()
method, on GC.SuppressFinalize(this);
, and on Dispose(bool disposing)
and all its contents ...
Looking at other options, I saw the following implementation:
public void Dispose()
{
((IDisposable)connection).Dispose();
}
Of course, we have the following:
public void Dispose()
{
throw new NotImplementedException();
}
What I would implement as it is usually shown in web examples:
public void Dispose()
{
if (connection != null && connection.State == ConnectionState.Open)
{
connection.Close();
connection = null;
}
GC.SuppressFinalize(this);
}
Well, about the first implementation example with all those comments, I understood that there is an explanation of the implementation options here.
Can anyone help me understand the difference between these methods and the first method's comments?