I work in C#, and I've been pretty lax about using using
blocks to declare objects that implement IDisposable
, which you're apparently always supposed to do. However, I don't see an easy way of knowing when I'm slipping up. Visual Studio doesn't seem to indicate this in any way (am I just missing something?). Am I just supposed to check help every time I declare anything, and gradually build up an encyclopedic memory for which objects are and which are not disposable? Seems unnecessary, painful, and error-prone.
How do you handle this?
EDIT:
Looking at the related questions sidebar, I found another question which made it clear that Dispose()
is supposed to be called by the object's finalizer anyway. So even if you never call it yourself, it should eventually happen, meaning you won't have a memory leak if you don't use using
(which is what I suppose I was really worried about all along). The only caveat is that the garbage collector doesn't know how much extra memory is being held by the object as unmanaged stuff, so it won't have an accurate idea how much memory will be freed by collecting the object. This will result in less-ideal-than-usual performance by the garbage collector.
In short, it's not the end of the world if I miss a using
. I just wish something would generate at least a warning for it.
(Off-topic: why is there no special markdown for linking to another question?)
EDIT:
Ok, fine, stop clamoring. It's super duper all-fired dramatic-chipmunk-level important to call Dispose()
or we'll all die.
Now. Given that, why is it so easy — hell, why is it even allowed — to do it wrong? You have to go out of your way to do it right. Doing it like everything else results in armageddon (apparently). So much for encapsulation, huh?
[Stalks off, disgusted]
FxCop might help (although it didn't spot a test I just fired at it); but yes: you are meant to check. IDisposable
is simply such an important part of the system that you need to get into this habit. Using intellisense to look for .D
is a good start (though not perfect).
However, it doesn't take long to familiarize yourself with types that need disposal; generally anything involving anything external (connection, file, database), for example.
ReSharper does the job too, offering a "put into using construct" option. It doesn't offer it as an error, though...
Of course, if you are unsure - try using
it: the compiler will laugh mockingly at you if you are being paranoid:
using (int i = 5) {}
Error 1 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'