Just to add to what's already been said:
It's important to realize that there are objects, and there are references (variables), and these are not the same thing.
When you write var a = new object();
you're doing two things:
- Creating a new
object
instance. This instance has no "name" -- just a location in memory. It is what it is. But, just so we have something to call it, let's call it "Bob."
- Declaring a variable
a
, which references the object
just created.
Now, when you write a = null;
, you're doing nothing to Bob. You're changing a
to reference, instead of Bob, null
, or in other words, "no object." So you can no longer access "Bob" using a
.
Does this mean now Bob doesn't exist? No. Bob's still right where he was.
Consider this (which is basically the scenario Henk mentioned):
var a = new object(); // Again, we're calling this object Bob.
object b = a;
Now, b
is another variable, just like a
. And just like a
, b
references Bob. But again, just as with a
, writing b = null;
does nothing to Bob. It just changes b
so that it no longer points to an object.
Here's where I'm going with this. You seem to have been under the impression that doing this:
a.Dispose();
...somehow also did this:
a = null;
...which was somehow equivalent to doing this:
Bob
= null; // now
Bob
is no object?
But if that were the case, then b
(above) would now point to no object, even though it was never set to null
!
Anyway, from my explanation above, hopefully it is clear that this is simply not how the CLR works. As Jon has pointed out, the IDisposable
interface is actually not related to memory being freed. It is about releasing shared resources. It does not -- cannot -- delete objects from memory, as if it did then we would have the behavior I've described above (references suddenly becoming invalid out of nowhere).
I know this was only loosely related to your specific question about IDisposable
, but I sensed that this question was coming from a misconception about the relationship between variables and objects; and so I wanted to make that relationship clearer.