Here are two classes that allocate resources, the first class needs to implement a custom destructor and standard Dispose, but the second class doesn't need either.
The difference is that the first class allocates resources in the constructor and doesn't clean them up immediately. In contrast, the second class allocates resources in a member function and carefully frees them before exiting (using a finally block), so the second class author doesn't need to bother writing Dispose and a destructor.
class MustDispose
{
public MustDispose()
{
create a 3rd party object
open a file handle
allocate some memory
open a database connection
open a network port
}
~MustDispose()
{
// customized destructor for this class
if (3rd party object != null) free the 3rd party object
if (file handle != null) close the file handle
if (memory != null) free the memory
if (connection != null) close the database connection
if (port open) close the network port
}
public void Dispose()
{
// because this class needs a destructor, it also needs this
// idiomatic Dispose method
Finalize();
System.GC.SuppressFinalize(this);
}
}
class NoDispose
{
public NoDispose()
{
// this class has an uninteresting constructor so it doesn't need
// a destructor or Dispose
}
MemberFuncThatCleansUp()
{
try
{
create a 3rd party object
open a file handle
allocate some memory
open a database connection
open a network port
}
finally
{
if (3rd party object != null) free the 3rd party object
if (file handle != null) close the file handle
if (memory != null) free the memory
if (connection != null) close the database connection
if (port open) close the network port
}
}
}
If a class needs a destructor, you should customize how it is written. However, the Dispose method has become an idiom in C# for any class that needs a destructor:
Gowtham RajamanickamPosted Dec 29, 2015, 4:38 AM
good one