开发者

How to fix CA2000 code analysis error on new DataTable instance

开发者 https://www.devze.com 2023-01-22 02:59 出处:网络
How to fix CA2000 code analysis error in following function on statement DataTable dtSummary = new DataTable(\"Summary\");? CA2000 going off If I use us开发者_如何学运维ing block on dtSummary and I ca

How to fix CA2000 code analysis error in following function on statement DataTable dtSummary = new DataTable("Summary");? CA2000 going off If I use us开发者_如何学运维ing 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; 

}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消