title: When and where to call dispose method c#?
body: <p>I have this below code to retrieve data from db and when I run the Code Analysis from Visual Studio, it suggests me to call dispose method on <code>SqlConnection</code>, <code>DataTable</code> and <code>SqlDataAdapter</code> objects.</p>
  
  <pre><code>        SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
          SqlCommand cmd = sqlconn.CreateCommand();
          cmd.CommandText = "SELECT * FROM tbl_serial WHERE serial = @serial";
          cmd.Parameters.AddWithValue("@serial", txtQuery.Text);
          DataTable dt = new DataTable();
          SqlDataAdapter da = new SqlDataAdapter();
          try
          {
              sqlconn.Open();
              da.SelectCommand = cmd;
              da.Fill(dt);
  
          }
          catch (SqlException ex)
          {
              lblStatus.Text = ex.Message;
          }
          finally
          {
              sqlconn.Close();
          }
  
          if (dt.Rows.Count &gt; 0)
          {
              lblStatus.Text = "FOUND!";
          }
          else
          {
              lblStatus.Text = "NOT FOUND!";
          }
  </code></pre>
  
  <p>And this is my first time doing this, I called dispose method on <code>sqlconn</code> just like this -</p>
  
  <pre><code>        finally
          {
              sqlconn.Close();
              sqlconn.Dispose();
          }
  </code></pre>
  
  <p>But then, Visual Studio warns me like this - </p>
  
  <blockquote>
    <p>CA2202 : Microsoft.Usage : Object 'sqlconn' can be disposed more than
    once in method 'test_search.Unnamed1_Click(object, EventArgs)'. To
    avoid generating a System.ObjectDisposedException you should not call
    Dispose more than one time on an object.: Lines: 41</p>
  </blockquote>
  
  <p>So I would like to know when should I correctly call dispose methods.</p>