We have code like below to fix CA2000: Dispose objects before losing scope (http://msdn.microsoft.com/en-us/library/ms182289.aspx). When the tbl is assigned null, will the object that it referenced garbage collected ?
private DataTable BuildRequestDataTable(Factory tableFactory)
{
DataTable tbl = null;
DataTable requestTable = null;
try
{
tbl = tableFactory.CreateTable();
requestTable = tbl;
tbl = null;
}
finally
{
if (tbl != null)
{
tbl.Dispose();
}
}
return requestTable;
}
No. Or at least, not immediately. Objects aren’t reference-counted like that.
It’s not really clear why you’re juggling all those variables at all – I can’t see how you’d ever end up disposing of anything. Either the
CreateTablecall succeeds, in which case the following two statements will succeed and nothing will be disposed, or theCreateTablecall throws, in which casetblwill still be null and nothing will be disposed.Your code is basically equivalent to:
At that point you may well get a warning that you’re not disposing of the
DataTable, but that’s deliberate – the caller would presumably take responsibility for disposing it.Of course at this point it’s not clear that the code is really providing much benefit itself – it’s no easier to use:
than
… unless you’re planning to add more logic in the method.