Take the 2-minute tour ×

I have an issue in my SharePoint environment and I suspect that this code causes a memory leak. I'm passing a SPWeb object as a value parameter.

Will the SPWeb object instance get disposed correctly using this code?

public void DoSomething(SPWeb web)
    // code here
public void mainProgram()
    using (SPWeb web = site.OpenWeb())
        //another code here
share|improve this question

2 Answers 2

up vote 2 down vote accepted

When you pass an object to a method by value, in the method you get simply copy of reference to the same object. No new objects is created, this mean that your code is correct. We need to dispose such object as spweb and spsite because they are using external resources (that require memory), and this resources not destroyed by garbage collector, we had to explicitly call method to remove it and free memory.
When you stop using your web object (right after "}") external resource for this particular object will be free, that's why all is correct.
You can try to verify your code using SPDisposeCheck tool. From my practice when you are using SPLimitedWebPartManager you need to explicitly dispose internal web webPartManaber.Web.Dispose(); (that is not so obvious at a first glance)

share|improve this answer
If you use the SPDisposeCheck tool to check your code, be aware that in some case it will report false positives when an instance is getting disposed outside the scope of the current method (most time, it will warn you that the instance may be disposed by the caller). The above answer still stands right, with your current code the SPWeb instance passed as a parameter will be correctly disposed even if the SPDisposeCheck tool may complain otherwise. –  SPArchaeologist Dec 23 '11 at 13:34
The general rule for .Net is that you must explicitly release any resources you create that implement the IDisposable interface; that is, that have a Dispose() method. If you are curious about an object, check to see if it has a Dispose() method. If it does and you created the object, then it is up to you to destroy it. SharePoint can be a little tricky in this regard because it does have methods that create objects when called where it is not immediately clear that they must be managed. –  Dave Wise Dec 23 '11 at 16:17

That code will dispose the SPWeb object correctly with the using statement. If an exception is thrown in the method, it will still get disposed.

share|improve this answer
Correct, because of the simple fact that objects are passed by reference by default in C#, thus the SPWeb within the DoSomething method points to the same SPWeb as created in mainProgram. Therefore its sufficient to dispose it in mainProgram only. –  Koen Zomers Oct 17 '12 at 12:01

Your Answer


