Should I pass my SPWeb object to a method or recreate it in that method?


Always pass it when possible but also make sure that any routines that you pass it to do not explicitly .Dispose() of it or use it in a using{} statement as that would Dispose() of the object earlier than expected. This would in turn cause all sorts of strange behavior for subsequent method calls.

|improve this answer|||||
  • 2
    There should be an Exception thrown when you try to access a previously disposed SPWeb object. But definitely one to watch for. – James Love Oct 28 '11 at 18:27

This probably goes without saying, but a valid point nonetheless:

If you need to elevate privileges, you will need to create a new one inside an SPRunWithElevatedPrivileges code block, and also make sure you dispose of it.

|improve this answer|||||

The answer depends upon the context in which your method is used.

You might start by restating as a classical object oriented programming delimna. In general, when writing a method that could access an object, do you want to pass the object or enough information to create it on demand? The answer based on performance is whether it costs you more to keep the object around or create it again. The performance answer often comes down to what is more expensive in your system, memory or processing. But in a managed memory system like .Net, often it comes down to the principle of keeping smaller objects in memory for short amounts of time. Discussions of object lifetime related to the .Net Garbage Collector can be found in books like Solid Code published by Microsoft Press.

In general, I would say the SPWeb object is small enough that I could recreate it when needed. Whatever you do, keep in mind the best practices for disposing SharePoint objects when doing either.

Also, keep in mind that the number one bullet in the list of common caused for instability in SharePoint applications is failure to dispose of SPWeb and SPSite objects after use. This reason alone should make you be careful about the situations in which you do pass around SPWeb objects because of the unknown state of their creation and required disposal. In Microsoft's SharePoint Guidance, refer to the chapter on Execution Models in SharePoint, Farm Solutions section for more information on stability.

|improve this answer|||||

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.