Jeff said:
Thanks, Matt, that's an excellent suggestion and the article provided
good detail.
If I'm reading the blog correctly there's no reason to Close the
stream since I know it's a memory-only resource. If there was any
question (say it was passed in as a reference), I should certainly
Close it when done.
I'm using VB right now, but when I get back to C#, I'll remember the
using trick. It doesn't look like there's a VB equivalent.
Well, there is actually. All using does is wrap the code in a try/finally
block and in the finally block it tests to see if the object implements
IDisposable, and if so, it calls Dispose. You have to write that code by
hand in VB.NET but its only a handful of lines to type.
In general, if an object implements IDisposable it means that it has a
resource that should be released as soon as possible, and hence you should
use the using or Try/Finally block as mentioned. However, there are
exceptions and unfortunately the documentation does not tell you about
these.
One example is Pens. This class has static/Shared properties like Black,
which will return a black Pen. Pen has a dispose method and it is based on a
GDI object so you *should* release a Pen as soon as possible. However, don't
do that with Pens. The reason is that this class has lazy initialization, so
the first time you access Pens.Black it will create a Black Pen and cache
this in a static field. The next time that you access Pens.Black it will
return the static field. If you call Dispose on this Pen then the object
will be disposed, but not released (the reference is not null/Nothing), so
Pens does not know that the Pen has been disposed and will return a disposed
object from Pens.Black. At this point there is no way to recreate the Pen
because Pens.Black checks to see if the reference is null, not if the object
is disposed.
The moral is that if an object has Dispose then you should use it... but
don't do this for all objects <g>.
Richard