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:
- // Using Dispose and Finalize method together
- public class MyClass : 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)
- {
- // TO DO: clean up managed objects
- }
-
- // TO DO: clean up unmanaged objects
-
- disposed = true;
- }
- }
-
- //At runtime C# destructor is automatically Converted to Finalize method
- ~MyClass()
- {
- Dispose(false);
- }
- }
Example for implementing the dispose method
- public class MyClass : 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)
- {
- // TO DO: clean up managed objects
- }
-
- // TO DO: clean up unmanaged objects
-
- disposed = true;
- }
- }
- }
No comments:
Post a Comment