title: Automatically Open and Close Database Connection Within a Method
body: <p>I have recently been put on an existing project and am trying to reduce the amount of duplicate code. </p>
  
  <p>Right now there are many methods relating to database interaction. The Database connection is opened and closed within each of these methods. Essentially, the exact same code is used in every single method to open and close the connection.</p>
  
  <pre><code>    public static void AddToTable()
      { 
          DbConnection con = Common.CreateConnection();
          DbCommand cmd = con.CreateCommand();
  
          //cmd.CommandText = SQL COMMAND GOES HERE
          //cmd.ExecuteNonQuery();
  
          con.Close();
      }
  </code></pre>
  
  <p>I understand the importance of opening and closing the connection but seeing these exact same lines of code in every method smells funny to me. </p>
  
  <p>Does C# have some kind of way I could accomplish automatically creating the connection (in this case the con and cmd variables) when the method is started and then closing the connection when the method is finished?</p>