Link to home
Start Free TrialLog in
Avatar of ad5qa
ad5qaFlag for United States of America

asked on

Using around DAO Objects

I would like to know if this is a good practice or not.

In our code it is recommended to put using statements around our data access objects.

Most of the time it is in a button event scope anyway, it should just gc correct?
if (SOMETHING)
{
        using (CustomersDao dao = CustomersDao())
        {
		//Do something with the object
        }
}
    else
    {
         using (CustomersDao dao = CustomersDao())
         {
                //Do something with the object
         }
    }
}
 
 
WHY NOT
 
 
CustomersDao dao;
if (SOMETHING)
{
        dao = new CustomersDao();
        {
		//Do something with the object
        }
}
    else
    {
        dao = new CustomersDao();
        {
		//Do something with the object
        }
    }
}

Open in new window

Avatar of Marcus Keustermans
Marcus Keustermans
Flag of South Africa image

Hi,

When you use the Using Key word it generates a try finally block in the back ground and it calls IDisposable.Dispose() in the finally block.  Please note however that it does not generate  a catch block

Making Use of Using  can however cause issues if IDispoasble.Dispose() is not properly implemeted.

The Using statement is normally used if you want to release resources a soon as possible instead of waiting for the gc to this for you.

Hereis a link for you so that can read up on it: http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx


Your using code above is equivalent to

if (SOMETHING)
{
        CustomersDao dao = CustomersDao();
        try
       {
            //Do something with the object
       }
       finally
       {
               dao.Dispose();
       }
}
else
{
          CustomersDao dao = CustomersDao();
        try
       {
            //Do something with the object
       }
       finally
       {
               dao.Dispose();
       }
}
               



Avatar of ad5qa

ASKER

I guess in a page that could possibly have many of the same object to be sure that gc runs for that scope you would use it. Otherwise if it is a small object and a short visit then dont bother.

I suppose it is a best practice when things get complacated and to ensure the scope of the object.
ASKER CERTIFIED SOLUTION
Avatar of Marcus Keustermans
Marcus Keustermans
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial