If a class implements the IDisposable interface, it will have a Dispose() Method. A simplified explanation for Dispose() would be, a place where you free up resources that garbage collector may not know to free. Consider the example below
Every class that implements IDisposable, would have customized use for its Dispose method. For example, in .net class library, one of the classes that implements IDisposable is SqlConnection Class. In the SqlConnection Class, the Dispose() method returns the connection object back to the connection pool.
A few points to note
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class GetDataFromFile:IDisposable
{
public void Dispose()
{
//perform clean up here
//eg close the file handle
}
public string
ReadFile()
{
string fileData = "";
//some code that reads the file will go in here
return
fileData;
}
}
class Program
{
static void Main(string[] args)
{
GetDataFromFile GF=new
GetDataFromFile();
string data;
try
{
data = GF.ReadFile();
}
finally
{
GF.Dispose();
}
}
}
}
A few points to note
- If you are freeing up resources in the Dispose, it is advisable that these resources should be freed in the destructor too. The reason being, if your class is being used by someone who forgets to call the Dispose(), then the freeing up of resources would still be performed when the garbage collection kicks in.
- If an object's Dispose method is called more than once, the object must ignore all calls after the first one. It should not throw an error.
- As a general rule, if you do not need to free up any unmanaged resources, you do not need to implement the IDisposable interface.
- try{data= GF.ReadFile();}finally{GF.Dispose();}can also be written asusing (GetDataFromFile GF = new GetDataFromFile()){data = GF.ReadFile();}
No comments:
Post a Comment
Comments will appear once they have been approved by the moderator