Search code examples
c#.netusing-statement

Is it valid to use properties of Disposing object


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.


Solution

  • It depends on the type, but as a general rule you should only call Dispose() when you are completed done using the object. Most IDisposable implementations will throw an ObjectDisposedException 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 object B, that doesn't mean that object B becomes invalid to use when you dispose A.

    A good example of this would be the NetworkStream class, which has a Socket property. If you initialize the NetworkStream object as not owning the Socket instance passed to its constructor, then the Socket instance remains valid for use after disposing the NetworkStream, and this is perfectly fine.