Control Life of aggregated object

T

Tony Maresca

I have a general question on how to best go about
controlling the lifetime of an aggregated object.

public class Contained : IDisposable
{
public void Dispose()
{
// cleanup
}
}

public class MyContainer : IDisposable
{
public void Dispose()
{
m_Contained.Dispose();
}

public MyContained Contained
{
get
{
return m_Contained;
}
}
private Contained m_Contained = new Contained();

}

When a client references the Contained property, I want
to prevent them from disposing the returned instance.

BTW, let's assume that I don't own Contained, it is
class from another library, which I'm consuming. Let's
further assume that Contained may be sealed.
 
C

cody

You do do some kind of reference counting.
The best way is to provide no accessor for the contained disposible object,
just helper methods to invoke necessary methods of it:

public class MyContainer : IDisposable
{
public void Dispose()
{
m_Contained.Dispose();
}

public void Foo()
{
m_Contained.Foo();
}

private Contained m_Contained = new Contained();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top