Yup, although they're generally written with the destructor-like
syntax. You should very, very rarely need one though - only when you
*directly* hold unmanaged resources. If you only have a reference to
something else which holds unmanaged resources (e.g. a Stream) then
just implementing IDisposable is enough. Allow the Stream itself to
clean up on finalization if nothing else has cleaned it up by then.
Well, I was going to open a file for logging, and close the file at
the program's end. So, i thought I needed a finalizer. I mean, the
file doesn't close itself, does it? Or is that what Dispose is
precisely for, and perhaps it implements this. It's hard to say from
a newcomer's perspective if I have direct management of the resource
or not, such as opening / closing a file.
No. The finalizer will be called *at some point* after the object is
eligible for finalization, i.e. when there are no more references to
it. There's no guarantee when that will be, or even necessarily whether
it will happen (e.g. during application termination).
Yes, I knew about multiple references, I guess I was asking this in
terms of that being the only reference. I know C# removes the need
for me to worry about cleaning up. But, what's confusing is for
things NOT like classes and arrays, but files that I think I am
supposed to be the one manually telling it to close.
It may or may not be usable - it depends on the implementation of
Dispose. Most of the time, it's not usable, and you would rarely use
the code pattern you showed - normally you declare the variable in the
using statement itself.
Yes, I can follow I can not used the variable inside of the using
statement itself since it goes out of scope, but dealing with a
variable whose Dispose method has been automatically called, but still
is in scope, is confusing.
Right, i should know that C# doesn't guarantee when any object is
cleaned up, since the GC does it on its own clock. Which is the
reason using-statement exists, for things that must be cleaned up
right then and there.
No, x.Dispose doesn't get called, and neither does the finalizer
automatically - not at the point at which the variable falls out of
scope. Bear in mind that by then, there may be other references to the
same object (because x could have been passed to methods, etc). .NET
doesn't do reference counting, due to both the performance penalty and
the problem of cyclic references.
Yes, again, I knew about the multiple reference possibility. So,
using-statement just forces Dispose to be called at the end } where a
normal end } just says to the GC "you can clean this up when you
like" (provided there are no other references).
Zytan