Q1: What happens to the object that is reference by manage (type
variable) after end of using statement? Means is it destroyed or CLR
decide to destroy when it needs?
It happens whatever happens to a local method reference.
Q2: How we can check that whether an object that is not reference by
any type variable is destroyed or not during execution of my
programme?
I'll answer this question with a new question: how can you check a reference against any condition if you don't own the whole reference? An object lives in memory unless there's no reference pointing to that given object. Otherwise, the garbage collector will collect it as soon as it's fired automatically by the CLR. In other words: if your program has no reference to an object, you can be sure that object will be garbage-collected.
That is, the garbage-collector may collect the object implementing IDisposable
and it'll be able to reclaim its memory but the underlying resources required and used by the whole object will be still alive because the garbage collector won't call IDisposable.Dispose
for you.
The problem with your question: IDisposable pattern has nothing to do with garbage collection
IDisposable
interface has nothing to do with garbage collection. It's just an interface to define objects capable of releasing resources. These resources can be whatever:
- A file system lock.
- A TCP port.
- A database connection.
- ...
Usually, IDisposable
is implemented by classes handling unmanaged resources and, since they're unmanaged, you need to manually dispose them. Otherwise, they would be released by garbage collector (which handles managed resources, of course...).
In the other hand, using
statement is just a try-finally
simplification:
using(ManageMe manage = new ManageMe())
{
manage.Add(4,8);
Console.WriteLine("using statement executed");
}
...is:
ManageMe manage = new ManageMe();
try
{
manage.Add(4,8);
Console.WriteLine("using statement executed");
}
finally
{
manage.Dispose();
}
Thus, as I said in my answer to your Q1, an using
block is just syntactic sugar to be sure that IDisposable.Dispose
method will be called once the block ends. The using
block expects an IDisposable
which can be either a variable declaration of the IDisposable
itself:
ManageMe me = new ManageMe();
using(me)
{
}