Free Web Development Online Tutorials, Learn to Code
IDisposable interface c#, Learn C# programming Language, Free C# Tutorial for Beginners

IDisposable Interface Implementation

IDisposable interface example in C#

IDisposable Interface C#

Here you learn how to implement IDisposable in C#, but before that you must realize that why do you need to implement IDisposable interface.

IDisposable provides a mechanism for releasing unmanaged resources in .Net

Just assume that you have a class called StudentDTO in your data access layer, now whenever you need to access student data in your presentation layer or controller, you need to create a new instance of StudentDTO class, right ?

Probably you will do this way
StudentDTO _dto=new StudentDTO();
// now here you call all students methods to complete your work.

What if you forget to set the new instance to null _dto=null; (after doing your work)! so the memory on heap will not be released, right ?
Now after implementing IDisposable in any class that can be done automatically, see the example.

dispose c# class object

Here you learn how to dispose c# class object using Dispose method of IDisposable Interface

public class StudentDTO:IDisposable
{

    // Dispose() calls Dispose(true)
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

IDisposable Implementation Example

Take a look at the complete implementation of IDisposable Interface of C# Class

public class StudentDTO:IDisposable
{
#region IDisposable Members
            
    private bool isDisposed = false;
    // Dispose() calls Dispose(true)
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
            
// NOTE: Leave out the finalizer altogether if this class doesn't
            
// own unmanaged resources itself, but leave the other methods
// exactly as they are.
            
    ~StudentDTO()
    {
        // Finalizer calls Dispose(false)
        Dispose(false);
    }
            
    // The bulk of the clean-up code is implemented in Dispose(bool)
    protected virtual void Dispose(bool disposing)
    {
    if (isDisposed)
    return;
        if (disposing)
        {
        // if any managed resources to be free.  
            
        }
    isDisposed = true;
    }
#endregion
}

Now you can create an instance of class this way, and you don't need to set the dto=null for this code

using (StudentDTO dto = new StudentDTO())
{
DataSet _ds= dto.getStudentDataset();
}

idisposable example

The moment your logic comes out of the curly brace { }, the object will be disposed automatically.

Comment
Name
Email
Website
Subscribe