Re: Simple Dispose Question
From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 02/24/05
- Next message: Nurchi BECHED: "Re: Question for RegEx gurus"
- Previous message: Michael S: "Re: Why does this object need to be cast?"
- In reply to: Jeff B.: "Simple Dispose Question"
- Next in thread: Jeffrey Palermo, MCAD.Net: "Re: Simple Dispose Question"
- Reply: Jeffrey Palermo, MCAD.Net: "Re: Simple Dispose Question"
- Messages sorted by: [ date ] [ thread ]
Date: Thu, 24 Feb 2005 07:16:20 -0000
Jeff B. <jsb@community.nospam> wrote:
> If an object implements the IDisposable interface, should I always call the
> Dispose method or is just setting it to null and letting the GC handle it
> sufficient? Here is the pattern I've been using but wasn't sure if it was
> necessary:
>
> DataAdapter da = null;
>
> try {
> // Some logic here...
> } catch (Exception ex) {
> // Some exception handling logic here...
> } finally {
> // Clean up...
> if (da != null) {
> da.Dispose();
> da = null;
> }
>
> Is the above necessary or could I just set da = null in the "finally" clause
> and be good?
An equivalent but simpler solution would be to use the using statement:
using (DataAdapter da = ...)
{
...
}
(You can put a try/catch inside the using statement if you really want
- most of the time you should let exceptions propagate up.)
Relying on the garbage collector to release unmanaged resources is a
very bad idea - there's no guarantee about when it will finalize the
object.
-- Jon Skeet - <skeet@pobox.com> http://www.pobox.com/~skeet If replying to the group, please do not mail me too
- Next message: Nurchi BECHED: "Re: Question for RegEx gurus"
- Previous message: Michael S: "Re: Why does this object need to be cast?"
- In reply to: Jeff B.: "Simple Dispose Question"
- Next in thread: Jeffrey Palermo, MCAD.Net: "Re: Simple Dispose Question"
- Reply: Jeffrey Palermo, MCAD.Net: "Re: Simple Dispose Question"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|