Re: Disposing Collections
- From: Helge Jensen <helge.jensen@xxxxxxx>
- Date: Wed, 25 May 2005 19:42:54 +0200
gmccallum wrote:
Thank you. Is there a way to tell in code if an object implements the Dispose method without having to try...catch exceptions.
For example [not meant to be c# code] if (isdisposable(class1)) class1.dispose()
IDisposable objects (usually) represents resouces which should be released at-once when you are done using them. This introduces a concept of "ownership" of the disposable.
You shouldn't Dispose() just because you are passes an IDisposable. only the "owner" should do that.
Usually ownership is on the callstack, which fits the "using" idiom very nicely, Example:
class Foo {
void WriteTo(Stream s) {
s.Write(...);
// just use stream, don't dispose
}
void f() {
using ( Stream s = new File.Open("foo") ) // "own" s
WriteTo(s);
}
}Another case is where objects have "owned" members, they often become resources themselves, becoming candidates for disposal:
class Bar: IDisposable {
Stream s;
public Bar() { s = new File.Open("foo"); }
public void Dispose() {
GC.SuppressFinalize(this);
if ( s != null ) {
s.Dispose();
s = null;
}
}
~Bar() {
// This code should not run in well-written programs
Errors.ForgottenDispose(this);
Dispose();
}
}
-- Helge Jensen mailto:helge.jensen@xxxxxxx sip:helge.jensen@xxxxxxx -=> Sebastian cover-music: http://ungdomshus.nu <=- .
- References:
- Disposing Collections
- From: gmccallum
- Re: Disposing Collections
- From: Carlos J. Quintero [.NET MVP]
- Re: Disposing Collections
- From: gmccallum
- Disposing Collections
- Prev by Date: Re: HKEY_LOCAL_MACHINE Registry Access
- Next by Date: Re: Help with Type.InvokeMember in C#
- Previous by thread: Re: Disposing Collections
- Next by thread: Writing to Registry
- Index(es):
Relevant Pages
|