2

How to fix CA2000 code analysis error in following function on statement DataTable dtSummary = new DataTable("Summary");? CA2000 going off If I use using block on dtSummary and I can't use using block in below function becuase some other function is going to use return datatable from GetSummaryReportTable function.

private DataTable GetSummaryReportTable(IImportResult result) {

DataTable dtSummary = new DataTable("Summary");
dtSummary.Columns.Add(STATUS_STRING_COL_NAME, typeof(string));
dtSummary.Columns.Add(STATUS_COL_NAME, typeof(int));
DataRow dataRow;

foreach (ReportErrorLevel error in distinctErrors)
{
    dataRow = dtSummary.NewRow();
    dataRow[STATUS_STRING_COL_NAME] = error.ToString();
    dataRow[STATUS_COL_NAME] = Convert.ToInt16(error);
    dtSummary.Rows.Add(dataRow);
}           
return dtSummary; 

}

user446573
  • 71
  • 1
  • 2
  • 5
  • Please format your code selecting it and the using the 101010 button. It is unreadable this way... – Lorenzo Oct 28 '10 at 00:13
  • possible duplicate of [Should I Dispose() DataSet and DataTable?](http://stackoverflow.com/questions/913228/should-i-dispose-dataset-and-datatable) – Luke Girvin May 27 '15 at 09:35

2 Answers2

2

This is topic has been discussed thoroughly here: Should I Dispose() DataSet and DataTable?.

In short, if you really want to follow the style cop rules then you can't use DataTable as a return type. You must use some other object to return your data and wrap the DataTable object in a using statement.

Community
  • 1
  • 1
Nate Totten
  • 8,904
  • 1
  • 35
  • 41
1

Check this out: http://connect.microsoft.com/VisualStudio/feedback/details/535110/ca2000-false-positive#details

Using the example...

Private Function GetNewStream() As StreamWriter

    m_CurrentFileName = GetNewFileName()

    // Triggers CA2000
    Return New StreamWriter(New FileStream(m_CurrentFileName, _
        FileMode.Append, _
        FileAccess.Write, _
        FileShare.Read))

End Function

Microsoft says:

"The reason why the rule is firing is because if StreamWriter's constructor throws an exception, then the newly created FileStream object is not getting disposed. You can fix this by wrapping it in a try/finally block and dispose the FileStream object in the finally block only if the StreamWriter block was not created successfully."

That seems like a superior way to resolve the warning.

Nick Spreitzer
  • 10,242
  • 4
  • 35
  • 58