hi friends,when we use using for defining an object?for example:
using (Login objLogin = new Login())
i know that we use when we want to clean the memory after using this object but i dont know when should we clean the memory.
hi friends,when we use using for defining an object?for example:
using (Login objLogin = new Login())
i know that we use when we want to clean the memory after using this object but i dont know when should we clean the memory.
The using
statement should be used to timely dispose of objects which implement IDisposable
. This does not actually clean managed memory but allows a managed object to release any unmanaged resources it may be holding and in some occasions remove references to managed objects to prevent memory leaks.
I suggest reading up on the following sites which provide in depth explanations of both IDisposable
and the using
statement
Whenever an object is disposable (it implements IDisposable interface) it means that it probably uses some unmanaged resources that can not be managed by garbage collector and therefore if your object is collected these resources might remain in the memory causing some problems. The solution for this problem is :
1.To implement IDisposable interface in such kind of objects and to clear/close unmanaged resources in Dispose method (for example if you are using a disposable object inside your object it'd be better to have a Dispose method to call its dispose inside)
2.To call the Dispose method of disposable objects when they are not needed anymore but be careful cause reusing a disposed object can throw some exceptions. The using syntax that you mentioned is a short way of doing the same and it interprets this:
using(var obj=new myDisposableObject)
{
obj.Something();
}
into following :
var obj=new myDisposableObject();
try
{
obj.Something();
}
catch
{
throw;
}
finally
{
obj.Dispose();
}
thus you can always be sure that whatever happens the Dispose method of your object is always called.
You don't clean the memory; the object implementing IDisposable will clean its unmanaged resources in its Dispose method (or at least, that's the implication that the class is making by implementing IDisposable), and .NET will clean the memory when the object is collected.