2

If I wrap in a class an object that has the dispose method I'll need to implement the dispose method in the class too?

For example I have a class which wraps an instance of SQLiteConnection, should I need to implement the dispose method to call the SQLiteConnection one?

4

For example I have a class which wraps an instance of SQLiteConnection, should I need to implement the dispose method to call the SQLiteConnection one?

Yes.

If you have MySQLiteConnection which makes/opens a SQLiteConnection it will not automatically dispose of that member on garbage collection. You need to explicitly mark your wrapper as IDisposable and call the member SQLiteConnection::Dispose.

If you're just using the SQLiteConnection in the class, or you have a reference to one (but don't open/own it), the Robert Harvey's answer is correct - just use it as you would anywhere else.

  • I would advise against storing disposables as members. It complicates things needlessly in many cases. – RubberDuck Dec 13 '15 at 15:19
4

I have a class which wraps an instance of SQLiteConnection, should I need to implement the dispose method to call the SQLiteConnection one?

Nope. Just wrap your SQLiteConnection instantiation in a using statement.

using (connection = new SQLiteConnection())
{
    // use `connection` here
    // ...
} // `connection` is disposed here.

Because SQLiteConnection implements IDisposable, the connection object is automatically disposed when the using block goes out of scope (at the ending brace of the using statement).

If you are inheriting from SQLiteConnection, then inherit also from IDisposable and implement the Dispose() method, which will do any local cleanup that's needed in your descendant class and then call Dispose() on the parent SQLiteConnection class.

Further Reading
Using Statement (C# Reference)

  • But he says that he wants his class to wrap an IDisposable, he does not say that he wants his class to simply use an IDisposable. – Mike Nakis Dec 13 '15 at 9:37
  • @MikeNakis: Depends on whether you are using inheritance or composition. – Robert Harvey Dec 13 '15 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.