can anybody tell me if it is valid to use the properties of Disposing object ? for e.g. in the following code DataTable is getting Dispose but its property DefaultView is used later,
public DataView MyView { get; set; }
private void button2_Click(object sender, EventArgs e)
{
using (DataTable table = new DataTable())
{
using (DataColumn dc = new DataColumn("s"))
{
table.Columns.Add(dc);
MyView = table.DefaultView;
}
Debug.Write(table.Columns[0].ColumnName);
}
}
I don't get any error if i use MyView. but isn't it true that Disposing object dispose all its properties in this case DefaultView.
It depends on the type, but as a general rule you should only call
Dispose()when you are completed done using the object. MostIDisposableimplementations will throw anObjectDisposedExceptionif you try to access any member after disposing the object.There's nothing inherent about
IDisposablethat forces an implementing class to invalidate all access to all members upon disposal.Only if the type specifically documents that it allows you to call certain members after it's been disposed should you consider doing so. And personally, I'd try to stay away from using types that are implemented that way.
Note that this pertains to the object itself, not necessarily objects it references. That is, just because object
Ahas a property that references some other objectB, that doesn't mean that objectBbecomes invalid to use when you disposeA.A good example of this would be the
NetworkStreamclass, which has aSocketproperty. If you initialize theNetworkStreamobject as not owning theSocketinstance passed to its constructor, then theSocketinstance remains valid for use after disposing theNetworkStream, and this is perfectly fine.