I wanted to know if there are any conventions regarding disposal of disposable items nested inside another disposable item(in a property/public field, not as private members). For example, a DataSet contains DataTable(s) and a SqlCommand contains a SqlConnection.
The obvious thing would be for a class to dispose of all Disposable items it owns, and leave the rest. Does there exist such a convention? If it does, how does .NET libraries determine who owns what? How can I find out whether nested objects are being disposed?
PS: I have been wondering about this for a while, and apparently so have others : What gets disposed when SqlCommand.Dispose is called?
Edit 1 : Found out that disposing DataSet, does not dispose its tables.
// Fill dataset from sqldataadpater.
foreach (DataTable dt in dataSet.Tables)
{
dt.Disposed += Program.DisposedEventHandler2;
}
Console.WriteLine("Disposing dataset");
dataSet.Dispose(); //Event not fired here.
Console.WriteLine("Disposing datatables maually");
foreach (DataTable dt in dataSet.Tables)
{
dt.Dispose(); //Event fired here
}
#endregion