Note that there are some explanatory texts on larger screens.

plurals
  1. POTrying to understand the 'using' statement better
    primarykey
    data
    text
    <p>I have read a couple of articles about the using statement to try and understand when it should be used. It sound like most people reckon it should be used as much as possible as it guarantees disposal of unused objects.</p> <p>Problem is that all the examples always show something like this:</p> <pre><code>using (SqlCommand scmFetch = new SqlCommand()) { // code } </code></pre> <p>That makes sense, but it's such a small piece of code. What should I do when executing a query on a database? What are all the steps? Will it look something like this:</p> <pre><code>string sQuery = @" SELECT [ID], [Description] FROM [Zones] ORDER BY [Description] "; DataTable dtZones = new DataTable("Zones"); using (SqlConnection scnFetchZones = new SqlConnection()) { scnFetchZones.ConnectionString = __sConnectionString; scnFetchZones.Open(); using (SqlCommand scmdFetchZones = new SqlCommand()) { scmdFetchZones.Connection = scnFetchZones; scmdFetchZones.CommandText = sQuery; using (SqlDataAdapter sdaFetch = new SqlDataAdapter()) { sdaFetch.SelectCommand = scmdFetchZones; sdaFetch.Fill(dtZones); } } if (scnFetchZones.State == ConnectionState.Open) scnFetchZones.Close(); } </code></pre> <p>What I want to know is:<br /> • Is it okay to have 4, 5, 10 nested using statements to ensure all objects are disposed?<br /> • At what point am I doing something wrong and should I consider revision?<br /> • If revision <strong>is</strong> required due to too many nested using statements, what are my options?<br /><br /> You might end up with a formidable hierarchy, but your code should be quite efficient, right? Or should you only put, for instance, the <code>SqlDataAdapter</code> object in a using statement and it will somehow ensure that all the other objects get disposed as well?</p> <p>Thanx.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload