System.IDisposable

It only has one method
Provides a form of deterministic destruction


public interface IDisposable 
{
   void Dispose();
}

The Dispose method makes a call to GC.SuppressFinalize
Setting an object to null does not trigger the Dispose() method to be called
As a rule of thumb, when you use an IDisposable object you should declare and instantiate it in a using statement
This calls the Dispose method on the object in the right way.


using Statement

This provides a convenient syntax that ensures the correct use of IDisposable objects.

using (StreamReader myReader = new StreamReader("C:\temp\myfile.txt") 
{
}

The StreamReader is an example of a managed type that accesses unmanaged resources.
Any unmanaged resources or class libraries that contain unmanaged resources must implement the IDisposable interface.


This is equivalent to:

try { 
    StreamReader myReader = new StreamReader("C:\temp\myfile.txt");
}
finally
{
   (IDisposable)myReader.Dispose();
}

The using block ensures that the Dispose method is called even if an exception occurs.
It is possible to declare multiple instances of a type in a using statement.

using (StreamReader myReader1 = new StreamReader("C:\temp\myfile1.txt"), 
        StreamReader myReader2 = new StreamReader("C:\temp\myfile2.txt")
{
}


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext