I'm switching on Code Analysis on an older project. Most remarks that result I can understand, but the CA2000: Dispose objects before losing scope is hard to get right.
For instance, this code from an ASP.Net page:
private void BuildTable()
{
HtmlTableRow tr = new HtmlTableRow();
HtmlTableCell td = new HtmlTableCell();
tr.Cells.Add(td);
// add some controls to 'td'
theTable.Rows.Insert(0, tr);
// 'theTable' is an HtmlTable control on the page
}
Gives CA messages:
CA2000 : Microsoft.Reliability : In method 'BuildTable()', call System.IDisposable.Dispose on object 'tr' before all references to it are out of scope.
CA2000 : Microsoft.Reliability : In method 'BuildTable()', object 'td' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'td' before all references to it are out of scope. (and similar messages about the controls that are added to that 'td'.)
I can resolve the second problem:
private void BuildTable()
{
HtmlTableRow tr = new HtmlTableRow();
HtmlTableCell td = new HtmlTableCell();
try
{
tr.Cells.Add(td);
// add some controls to 'td'
td = null; // this line is only reached when there were no exceptions
}
finally
{
// only dispose if there were problems ('exception path')
if (td != null) td.Dispose();
}
theTable.Rows.Insert(0, tr);
}
But I don't think it is possible to resolve the message about the 'tr'. I can't Dispose of that, because it's still needed after the method has exited.
Or did I miss something?
By the way: changing that theTable.Rows.Insert
into theTable.Rows.Add
changes the CA message to 'not disposed along all exception paths'