For those of you playing the home game of “Should I dispose in SharePoint” may have noticed comments about edge cases like SPContext.Current.Site.RootWeb saying that the SPSite object automatically tracks the SPWeb objects that it creates and disposes them when it is disposed. I recently ran across some code that disposed of a SPSite object that they created and then returned the SPWeb object they created from the site to the caller. Here’s the problem with that…
The SPWeb object will already have been disposed by SPSite when it got disposed. Because of this fact that specific SPWeb that was created should never be used after calling .Dispose() on the SPSite. (You’re not supposed to use an object after having called it’s .Dispose() method.) Although the code *may* be working, it’s definitely not recommended because the object may throw an ObjectDisposed exception, it may transparently reconnect itself (meaning that it effectively ignored the dispose and starts camping out in memory), or may just start doing weird stuff.
[Edited: 2009-02-13 – Minor clarification to exactly what I meant about SPWeb being used after SPSite per comment.]
So … never dispose your SPSite until you’re sure you’re done using all of the SPWebs you’ve created from it.