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. MostIDisposable
implementations will throw anObjectDisposedException
if you try to access any member after disposing the object.There's nothing inherent about
IDisposable
that 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
A
has a property that references some other objectB
, that doesn't mean that objectB
becomes invalid to use when you disposeA
.A good example of this would be the
NetworkStream
class, which has aSocket
property. If you initialize theNetworkStream
object as not owning theSocket
instance passed to its constructor, then theSocket
instance remains valid for use after disposing theNetworkStream
, and this is perfectly fine.