return the variable used for using inside the using C#

di3go picture di3go · May 12, 2010 · Viewed 9.2k times · Source

I am returning the variable I am creating in a using statement inside the using statement (sounds funny):

public DataTable foo ()
{
    using (DataTable properties = new DataTable())
    {
       // do something
       return properties;
    }
}

Will this Dispose the properties variable??

After doing this am still getting this Warning:

Warning 34 CA2000 : Microsoft.Reliability : In method 'test.test', call System.IDisposable.Dispose on object 'properties' before all references to it are out of scope.

Any Ideas?

Thanks

Answer

Robert Harvey picture Robert Harvey · May 12, 2010

If you want to return it, you can't wrap it in a using statement, because once you leave the braces, it goes out of scope and gets disposed.

You will have to instantiate it like this:

public DataTable Foo() 
{ 
    DataTable properties = new DataTable();
    return properties; 
} 

and call Dispose() on it later.