Search code examples
c#sql-serversqlconnection

Is it safe to have a SqlConnection close in a classes destructor upon program completion in C#?


I have a class in C# called SQLServerConnection that holds a SqlConnection object. The class connects to a SQLServer with the SqlConnection instance. The class has a destructor as follows:

~SQLServerConnection()
{
    dbConnection.Close();
}

Upon program completion, an error is thrown at dbConnection.Close() with the following error:

System.InvalidOperationException: 'Internal .Net Framework Data Provider error 1.'

Any idea why this is happening? If I call Close() normally in the main class this works fine but only throws an error if done in the destructor.

Also, is it bad practice to close connections in destructors like this?


Solution

  • It looks like you want your class to encapsulate the out-of-the-box SqlConnection class, since it holds an instance of SqlConnection in dbConnection which I assume is a field on the class instance.

    The thing is that SqlConnection is IDisposable. So if your class wants to hold an instance of that in a field, that means your class should also be IDisposable. From Microsoft's CodeAnalysis rules (literally, it is rule 1001), see Types that own disposable fields should be disposable.

    You might also like to note the line on that page saying:

    If the class does not directly own any unmanaged resources, it should not implement a finalizer.