PeacefulSoul
PeacefulSoul

Reputation: 13

how to close a oledbconnection object?

ok so i have a Class A that implements method M1 that takes an excel path and a sheet name, and returns an OledbDataReader . Class B calls the method M1 , does some stuff with the OledbDataReader, then closes the OledbDataReader. but how can i Close The OLEDBConnection object? i dont have access to it because M1 in Class A opened the connection ! any ideas? thank youu

Upvotes: 1

Views: 2141

Answers (3)

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29640

You can remodel your class A like this:

class HelperClass : IDisposable
{
    private bool _disposed;
    private OleDbConnection _connection;

    public HelperClass()
    {
        _connection = << open the conection >>;
    }

    public OledbDataReader GetOpenedReader()
    {
        return << open your reader here with the connection >>;
    }

    public void Dispose()
    {
        if (!_disposed)
        {
            _disposed = true;

            _connection.Dispose();
        }
    }
}

Then it's the resposibility of the calling class to use your class like this:

using (var helperClass = new HelperClass())
{
    // call the method that opens the reader and uses it
}

Upvotes: 1

Andrey
Andrey

Reputation: 60115

Implement IDisposable in class A

Upvotes: 0

brumScouse
brumScouse

Reputation: 3226

IF you have a using in your outer class like so.

 using (OleDbConnection connection = new OleDbConnection(connectionString))
 {



}

This will dispose of it all in good time...

Upvotes: 1

Related Questions