I'm battling a bit to understand disposing of objects and garbage collection. In particular, I don't understand why I can still use a disposed object. I'm not trying to do anything practically, I'm just playing around with theory at the moment and in my understanding, I thought that I wouldn't be able to do the following:
class Program
{
static void Main(string[] args)
{
Person p = new Person();
using (p)
{
p.Name = "I am Name";
}
Console.WriteLine(p.Name); // I thought this would break because I've already disposed of p
Console.ReadLine();
}
}
public class Person : IDisposable
{
public string Name;
public void Dispose()
{
Console.WriteLine("I got killed...");
}
}
I'm hoping that someone could perhaps give me some direction or guidance here so as to clear up my misunderstanding of this concept?
Disposing of an object doesn't do anything magical - the CLR doesn't really care about IDisposable
at all... it's just a framework interface that has support within C# (and other languages). Calling Dispose
is just like calling other methods.
If you don't make a disposed object fail when you perform further operations on it, it won't. Indeed, there are some cases where you really want to be able to - for example, calling ToArray
on MemoryStream
is fine after it's disposed, even though you can't call Read
etc. That can be really handy in situations where the writes to a MemoryStream
are chained from a wrapper which will dispose of the MemoryStream
, but you want the data afterwards.
In general though, you should code as if you can't use a disposed object after disposal, unless you know for sure that it still supports the operations you need. A default position of "I expect it will break..." is a safe one.
See more on this question at Stackoverflow