While disposing the class instance, do i need to dispose all its IDisposable members explicitly?
Yes
Yes
There even exists a Code Analysis rule for that: CA1001: Types that own disposable fields should be disposable.
A class implements the IDisposable interface to dispose of unmanaged resources that it owns. An instance field that is an IDisposable type indicates that the field owns an unmanaged resource. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface.
EDIT: the above answer is always valid for IDisposable
members that are owned by the parent class.
That said, the ownership of a member is kinda vague for public properties like yours: if the SqlConnection
instance is created outside your class, chances are your class is not actually owning the instance, but nobody knows that except you.
There is a funny example about whether an IDisposable
member is owned or not by its parent class: StreamWriter
. There are lots of question about it, see for example this thread: Is there any way to close a StreamWriter without closing its BaseStream?
Now there even is a leaveOpen
parameter so the StreamWriter
doesn't dispose its base stream.
It depends. If your class creates and owns the IDisposable
it must dispose it (so, both answers are "yes").
If your class just uses IDisposable
it must not dispose it (so the first answer is, usually, "no" and the second answer is "no").
In your case, it seems that Helper
class
public class Helper
{
// Note, that you can assign any arbitrary Connection via this property
public SqlConnection SqlConnection { get; set; }
....
}
just uses SqlConnection
(because it provides "set") in the way like
// It's not helper that owns SqlConnection
using (SqlConnection con = new SqlConnection(...)) {
...
// helper just uses Connection, so helper must not dispose it
Helper helper = new Helper() {
SqlConnection = con;
};
...
}
so it must not dispose the connection. On the contrary, a class like that
public class Helper: IDisposable {
private SqlConnection m_SqlConnection;
// Note the absence of public "set"
public SqlConnection SqlConnection {
get {
return m_SqlConnection;
}
}
...
}
owns its SqlConnection
so it's responsible for disposing it:
using (Helper helper = new Helper(...)) {
...
// it's helper that owns SqlConnection
SqlConnection con = helper.SqlConnection;
...
}