Use the using
statement in the calling method, not the method returning the object.
public void Caller()
{
using(DataSet ds = GetDataSet())
{
// code here
}
}
public DataSet GetDataSet()
{
// don't use a using statement here
return ds;
}
The using
statement is basically the same as doing this:
DataSet ds = null;
try
{
// code here
}
finally
{
if(ds != null)
{
ds.Dispose();
ds = null;
}
}
So, if you used a using
statement in a method that is supposed to return the object in the using
statement, it would return a Disposed object (i.e. closed stream, closed dataset, etc...)which means some of the internal objects could be null, or closed. In other words, all of the internal resources would be cleaned up, which is the purpose of implementing IDisposable in the first place. If your application relied upon some of these internal resources to be available, for example when using a Stream object, it would throw an exception.
Also keep in mind that not all finally
blocks are written the same. Remember, IDispoable was implemented to clean up any INTERNAL resources and unmanaged objects. Those internal resources may not be needed outside the using
statement, so sometimes using the using
statement as you have may appear to work properly but it is not recommended, and definately won't work with all objects. If Microsoft decided to change the DataSet object in a future release, disposing of something vital to your application, then your working code would suddenly stop working.