Search code examples
c#idisposablesqlconnection

Using C#'s 'using' statement with a custom object's function, do I Need to implement IDisposable?


I have an sqlConnection manager class like so:

public class SQLConn {
  public string connStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];

  private SqlConnection sqlConn;

  public SqlConnection Connection()
  {
      sqlConn = new SqlConnection(connStr);

      return sqlConn;
  }

  public void Open()
  {
        sqlConn .Open();
  }
}

If I use a function with the 'using' statement like:

var conn = new SQLConn();

using (conn.Connection()) 
{ 
    String query = "Select * from table";
    objSql = new SqlCommand(query, conn.Connection());      

    conn.Open(); 
    DoSomething(); 
}

Does the using statement dispose of the connection automatically since conn.Connection() returns a SqlConnection object? Or, do I have to implement IDisposable and a custom Dispose method on the SqlConn class?

Is this even a good way at all? I'm working with legacy code and I'm not able to use an ORM yet but is there a way to simplify this existing pattern to manage/create SQL connections?


Solution

  • The using statement will look at the final type of the expression - i.e. whatever is returned from .Connection(); if this returns something that is IDisposable, then you're OK.

    The compiler will tell you if you get it wrong ;-p (it won't let you use using on something that isn't IDisposable).

    You should probably watch out for where you are creating two connections:

    using (var c = conn.Connection()) // <==edit
    { 
        String query = "Select * from table";
        objSql = new SqlCommand(query, c); // <==edit
    
        c.Open(); 
        DoSomething(); 
    }
    

    and possibly:

    public SqlConnection Connection()
    {
      if(sqlConn == null) sqlConn = new SqlConnection(connStr); // <== edit
      return sqlConn;
    }