Suppose, I have following classes:
public class DisposableObj : IDisposable
{
public ChildObj CreateObj();
internal object GetSomething();
// ...
}
public class ChildObj
{
private DisposableObj m_provider;
public void DoSomething()
{
m_provider.GetSomething();
}
// ...
}
It’s possible that at some point the disposable object will be disposed but child object will still have a reference to it.
If at this time user will call DoSomething method then child object will try to access disposed object. This is not good hence the question:
How should I properly design such classes?
UPDATE/CLARIFICATION:
I am aware of ObjectDisposedException and all. My question probably should sound like: how to properly notify user about exceptional situation and how design the classes to make maintaining them easier?
While that is a scenario that is technically possible, this should be an exceptional state in your progam – I can’t imagine why you would deliberately set up for this scenario.
Having said, that make it clear in your design who is responsible to dispose
DisposableObjand when – if any child accesses the disposed object afterwards you can argue that this should cause an exception – don’t work around this but throw an exception an let the exception bubble up so you can fix the logic when you discover the problem.Implementation-wise you can achieve this by just keeping a boolean that keeps track of whether
DisposableObjis disposed and on a later access just throwObjectDisposedException. To clarify I mean theDisposableObjobject itself should keep track of its state and throwObjectDisposedExceptionon any method call on it after it was disposed.