0

This question has to do with this post and some of the answers, especially the answer from @EricLippert .

I want to encapsulate reading and writing an Informix SE database inside of a C# class.

I want the OdbcConnection, OdbcCommand, and OdbcDataReader to be created when a class method is called, and remain as long as the class instance is active. I am assuming I need a C# finalizer to do this.

I believe that merely instantiating C# class in a using statement won't dispose what a class method creates. For example, I would need a finalizer in the following to make sure that m_dbCon gets cleaned up, when the class leaves the scope of the using statement.

Is this correct?

class icsDbIo
{
    private OdbcConnection  m_dbCon;
    private OdbcCommand     m_dbCmd;
    private OdbcDataReader  m_dbReader;
    private string          m_queryString;
    private string          m_dsn;

    public OdbcDataReader connectAndReturnDataReader()
    {
        m_dbCon = new OdbcConnection("DSN=bucky");
        .
        .
        .
        return m_dbReader;
    }
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
  • A `using` statement will explicitly call `Dispose`, just do that. – DavidG Jul 27 '17 at 17:08
  • Also, unless you have a good reason, you should probably be `using` the `OdbcConnection` inside the method too. General rule of thumb for database stuff: connect as late as possible, disconnect as soon as possible. – DavidG Jul 27 '17 at 17:10
  • I see this less as a duplicate and more as a furthering of the original question. I even referenced the first post. I believe I'm asking a different question. – octopusgrabbus Jul 27 '17 at 22:54

1 Answers1

3

The correct way to implement this is not with a finalizer, but by making icsDbIo itself IDisposable and creating it with a using statement. Then put the cleanup code in Dispose.

Exiting the using block will then clean up everything as you would hope.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117