Implementation of the IDisposable interface

The following code example shows the implementation of the IDisposable interface in a class named CustomerDataAccess. The class implements the Dispose method defined by IDisposable to provide a way to release resources explicitly. The Dispose method releases the resources with the help of a supporting custom-defined ReleaseResource method and removes the current object from the finalization queue. This relieves the garbage collector from calling the finalizer of an object after the object is disposed. The class also calls the ReleaseResource method in the finalizer or destructor to ensure that the garbage collector releases the unmanaged resources of the class, even if the Dispose method is not called explicitly.

Visual Basic

Public Class CustomerDataAccess Implements IDisposable Protected Overridable Sub ReleaseResource(ByVal disposing As Boolean) If disposing Then

' Call dispose on any objects referenced by this object End If

' Release unmanaged resources End Sub

Public Sub Dispose() Implements IDisposable.Dispose Me. ReleaseResource(True) GC.SuppressFinali ze(Me) End Sub

Protected Overrides Sub Finalize() Me. ReleaseResource(False) End Sub End Class

public class CustomerDataAccess : IDisposable {

protected virtual void Dispose(bool disposing) {

if(disposing) {

// call dispose on any objects referenced by this object

// release unmanaged resources

public void Dispose() {

this.Dispose(true) ;

GC. SuppressFinalize(this);

~CustomerDataAccess() {

thi s.Dispose(false);

Discussion: Categorizing the Uses of Common Interfaces

Was this article helpful?

0 0

Post a comment