Power of using Clause in SharePoint



Power of using Clause in SharePoint


The Using Clause will help to avoid memory leaks in SharePoint by automatically Disposing the MOSS objects.

For example when we create SPSite and SPWeb objects, if we don't dispose it explicitly it might create memory leaks,

the given below code is not a good practice as it might trigger memory leakage...

SPSite spSite = new SPSite("http://mysharepointserver");
SPWeb spWeb = spSite.OpenWeb();
SPUser spUser = spSite.SystemAccount;


the same code can be written with using clause like below to avoid memory leakage...

using (SPSite spSite = new SPSite("http://mysharepointserver"))
{
SPWeb spWeb = spSite.OpenWeb();
SPUser spUser = spSite.SystemAccount;
}


more details on avoiding memory leak on different situations can be found here