I have a class which implements IDisposable interface.
using System;
class A : IDisposable
{
public void Dispose()
{
Stop(); // some actions to stop internal threads
this = null;
}
}
Why can’t I assign this = null in Dispose method ? I know ‘this’ is read-only.
For example:
A a = new A();
a.Run();
// ...
a.Dispose();
// i want in this line a = null
I thought IDisposable and Dispose method guarantee that instance of class A will be equals to null after calling Dispose(). But it’s not true.
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:objectinstance. 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.”a, which references theobjectjust created.Now, when you write
a = null;, you’re doing nothing to Bob. You’re changingato reference, instead of Bob,null, or in other words, “no object.” So you can no longer access “Bob” usinga.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):
Now,
bis another variable, just likea. And just likea,breferences Bob. But again, just as witha, writingb = null;does nothing to Bob. It just changesbso 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:
…somehow also did this:
…which was somehow equivalent to doing this:
Bob= null; // nowBobis no object?But if that were the case, then
b(above) would now point to no object, even though it was never set tonull!Anyway, from my explanation above, hopefully it is clear that this is simply not how the CLR works. As Jon has pointed out, the
IDisposableinterface 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.