tags:

views:

48

answers:

3

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.

+3  A: 

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

JaredPar
+1  A: 

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.

Beatles1692
thanks,but i didint understand the last line of your answer,thus....i want know when an object use some unmanaged resources?
arash
@arash: I mean that even if an exception happens the Dispose method will always be called.Usually if an object is disposable it means that it uses unmanaged resources. Otherwise there's no straightforward way to realize that an object is using unmanged resources.
Beatles1692
A: 

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.

SnOrfus