C # 'use' of posing question

If you use the use clause to get rid of the connection, are other elements inside the clause that implement IDisposable also automatically deleted? If not, how do you manage to ensure that all IDisposable objects are automatically deleted?

public static DataTable ReturnDataTable( string ConnectionString, string CommandTextString, CommandType CommandType, int CommandTimeout, List<System.Data.SqlClient.SqlParameter> ParameterList = null) { using (System.Data.SqlClient.SqlConnection Connection = new System.Data.SqlClient.SqlConnection()) { Connection.ConnectionString = ConnectionString; System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand(); Command.Connection = Connection; Command.CommandText = CommandTextString; Command.CommandType = CommandType; Command.CommandTimeout = CommandTimeout; if (ParameterList != null) { if (ParameterList.Count > 0) { foreach (SqlParameter parameter in ParameterList) { Command.Parameters.AddWithValue( parameter.ParameterName, parameter.Value); } } } System.Data.DataTable DataTable = new System.Data.DataTable(); System.Data.SqlClient.SqlDataAdapter DataAdapter = new System.Data.SqlClient.SqlDataAdapter(); DataAdapter.SelectCommand = Command; DataAdapter.Fill(DataTable); return DataTable; } } 
+7
source share
3 answers

You can add such statements (initialize all disposable objects first)

 using (...) using (...) { ... } 

or you can use nested usage operators for each disposable object that you need.

 using (...) { using (...) { ... } using (...) { ... } } 
+7
source

Only the object created in the use clause will be deleted. If you want to make sure that a delete call is automatically created for each one-time object created inside the use block, you will need to wrap each of them in a usage offer (or you can just call or close, depending on what they support, the course ) So the answer is not like that.

+3
source

Not. You will need to explicitly call Dispose for those that are not in the parameters of the using statement.

+2
source

All Articles