0

What is difference between

SPSite spSite = SPContext.Current.Site;

 and

 SPSite spsite = new SPSite(SPContext.Current.Web.Url)

Which is good practice?

3

SPSite spsite = new SPSite(SPContext.Current.Web.Url) creates a new instance of the SPSite object, and you are responsible to dispose it. However, you don't need to dispose SPSite in SPSite spSite = SPContext.Current.Site;

  • I think its best never to dispose SPContext.Current.Site, because other objects might use it. – Remko Apr 2 '14 at 11:30
  • That is what I have written :-) – Nadeem Yousuf Apr 2 '14 at 11:30
  • a part of it.. you say you don't need.. ;-) – Remko Apr 2 '14 at 11:32
  • So I have to use USING block for case 1 – variable Apr 2 '14 at 11:35
  • or a Try/Catch/Finally, which is what USING gets converted to (well, Try/Finally). – wjervis Apr 2 '14 at 12:24
0

Well the first on uses the already existing site in the SPContext object.

The second one initiate a new SPSite object (from the url of the current site).

The second one should primarily be used when you use SPSecurity.RunWithElevatedPrivileges. That is because otherwise the site object will not be elevated.

Also, the second one is used when working with another site then the current (by passing in GUID or Url)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.