Reputation: 13
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
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
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