Object not located along all execution paths

I have the following code.

private DataTable LoadSMSCellProviders() { string sqlQuery = "Select * from SMSAddress"; DataTable dt = new DataTable(); using (SqlConnection conn = new SqlConnection(Utility.ConnString)) { using (SqlCommand command = new SqlCommand(sqlQuery, conn)) { SqlDataAdapter adapter = new SqlDataAdapter(command); adapter.Fill(dt); return dt; } } } 

Microsoft code analysis tells me that dt doesn't fit along all the execution paths, but I'm not sure how to fix this. If I try to call dispose on it before return , it will return a null value, and if I try to do this at the end of the method, the code will never be reached ...

What am I missing here?

This is a message from an analysis tool:

warning: CA2000: Microsoft.Reliability: in the 'xx ()' method, the 'dt' object is not located on all exception paths. Calling System.IDisposable.Dispose on the 'dt' object before all references to it is out of scope.

+6
source share
4 answers

You need to get rid of it when an exception occurs. Like this.

 private DataTable LoadSMSCellProviders() { string sqlQuery = "Select * from SMSAddress"; DataTable dt = null; try { dt = new DataTable(); using (SqlConnection conn = new SqlConnection(Utility.ConnString)) { using (SqlCommand command = new SqlCommand(sqlQuery, conn)) { SqlDataAdapter adapter = new SqlDataAdapter(command); adapter.Fill(dt); return dt; } } } catch { if(dt != null) dt.Dispose(); throw; } } 

The idea is that if an exception occurs, then there is no way to get rid of the DataTable , because it will not be passed back to the caller. So this is a template that will make code analysis happy.

+7
source

Turn the tool. Data tables do not need to be deleted. They are IDisposable because they inherit IComponent, but their Dispose () method does nothing. It seems disgusting to me that MS's own tool does not know this.

+3
source

Code analysis warns you that this object cannot be deleted. As @juharr rightly suggests, you must neutralize the code path where the exception occurs, otherwise the object will not be returned and it will not be explicitly deleted. This will save you a warning.

0
source

Check out @juharr's answer as well after using Datatable and you no longer need to do this

 using(dt){} 

and he will recycle it for you

-2
source

Source: https://habr.com/ru/post/978200/


All Articles