0

What is difference between

SPSite spSite = SPContext.Current.Site;

 and

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

Which is good practice?

2 Answers 2

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;

5
  • I think its best never to dispose SPContext.Current.Site, because other objects might use it.
    – Remko
    Commented Apr 2, 2014 at 11:30
  • That is what I have written :-) Commented Apr 2, 2014 at 11:30
  • a part of it.. you say you don't need.. ;-)
    – Remko
    Commented Apr 2, 2014 at 11:32
  • So I have to use USING block for case 1
    – variable
    Commented Apr 2, 2014 at 11:35
  • or a Try/Catch/Finally, which is what USING gets converted to (well, Try/Finally).
    – wjervis
    Commented Apr 2, 2014 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 and acknowledge you have read our privacy policy.

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