title: using statement with connection.open
body: <p>I was looking at some code and discussing it with co-workers.</p>
  
  <p>Specifically a section of code that looks like this.</p>
  
  <pre><code>    [Test]
      public void TestNormalWay()
      {
          using(var cn = GetConnection())
          {
              cn.Open();
              // do stuff
          }
      }
  </code></pre>
  
  <p>The question came up:</p>
  
  <blockquote>
    <p>"why not move the cn.Open into the GetConnection method."</p>
  </blockquote>
  
  <p>I said that if "Open" throws an exception dispose would not get called.  His response was </p>
  
  <blockquote>
    <p>"So what.  The connection wasn't opened so why would it need to get
    closed (or disposed)?"</p>
  </blockquote>
  
  <p>For me it is just a matter of not wanting to know if or if not I NEED to dispose/close so I would repeat the cn.Open in the code instead of moving it into the shared function.  </p>
  
  <p><strong>BUT</strong> it is interesting... so I did some reading at <a href="http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx" rel="noreferrer">SQL Server Connection Pooling (ADO.NET)</a></p>
  
  <p>To me it isn't clear if there exists a scenario in which calling cn.Open and it throws and exception where dispose would need to be called.</p>
  
  <p>So in my example below is there any difference really between "TestNormalWay" and "WhyNotDoItThisWay"</p>
  
  <pre><code>    protected static DbConnection GetConnection()
      {
          DbConnection cn = new SqlConnection("SomeConnecitonstring... ");
          return cn; 
      }
  
      protected static DbConnection GetConnectionDangerousVersion()
      {
          DbConnection cn = new SqlConnection("SomeConnecitonstring... ");
          cn.Open();  // this will throw.. .dispose not called
          return cn; 
      }
  
      [Test]
      public void TestNormalWay()
      {
          using(var cn = GetConnection())
          {
              cn.Open();
              // do stuff
          }
      }
  
      [Test]
      public void WhyNotDoItThisWay()
      {
          using(var cn = GetConnectionDangerousVersion())
          {
              // do stuff
          }
      }
  </code></pre>