Which code segment should you use?

You have a SharePoint site that has the URL http://contoso.com/hr.

You are creating a new Web Part.

You need to create a reference to the current subsite without having to dispose of any returned objects.

Which code segment should you use?

You have a SharePoint site that has the URL http://contoso.com/hr.

You are creating a new Web Part.

You need to create a reference to the current subsite without having to dispose of any returned objects.

Which code segment should you use?

A.
SPSite siteCollection = new SPSite(“http://www.contoso.com”);
SPWebCollection site = siteCollection.AllWebs;

B.
SPSite siteCollection = new SPSite(“http://www.contoso.com”);
SPWeb site = siteCollection.RootWeb;

C.
SPSite site = SPContext.Current.Site;

D.
SPWeb site = SPContext.Current.Web;

Explanation:
MNEMONIC RULE: “One-line SPWeb”

NEVER dispose of anything created with the use of SPContext objects, so your choice is now limited to answers C and D.
Since you need a reference to the subsite (in SharePoint world, subsite = web), answer D is correct.

SPContext objects are managed by the SharePoint framework and should not be explicitly disposed in your code. This is true also for the SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web.

Disposing Objects
http://msdn.microsoft.com/en-us/library/ee557362.aspx



Leave a Reply 0

Your email address will not be published. Required fields are marked *