0

Possible Duplicate:
What is the C# Using block and why should I use it?

If I ran the following code:

using (SPWeb web = SPContext.Current.Site.OpenWeb("/myweb")){

   //error happens here
}

Would the object web be disposed of properly if an error occurred before the closing bracket?

We were told that using using statements for our OpenWeb object was the best but
we are seeing a lot of errors in the logs about SPRequests and SPWeb.

Community
  • 1
  • 1
iambriansreed
  • 21,935
  • 6
  • 63
  • 79

2 Answers2

7

Yep, that's kind of the whole point. It's syntactic sugar for:

SomeType obj = new SomeType();
try
{
    // do stuff with obj
    // if an exception is thrown then the finally block takes over
}
finally
{
    if(obj != null)
        obj.Dispose();
}
Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • That's what I was told and always believed but we appear to be getting a lot of errors regarding the SPWeb. – iambriansreed Dec 20 '12 at 20:38
  • 1
    @iambriansreed: Either the C# compiler is broken or the bug is somewhere else. I'd suspect the latter. – Ed S. Dec 20 '12 at 20:39
  • I was told `SPWeb web = SPContext.Current.Site.RootWeb` should never be disposed. Is that true as well? – iambriansreed Dec 20 '12 at 20:40
  • Note that if the `Dispose` implementation of SPWeb throws an exception, that will *not* be handled. – vcsjones Dec 20 '12 at 20:40
  • @iambriansreed: I am not familiar with the SharePoint API, so I have no idea. Read the documentation. That said, it would seem to be correct as that object is probably intended to stick around. You don't own it. – Ed S. Dec 20 '12 at 20:40
  • The C# compiler will also do a null check on `obj` before calling Dispose, but yes this is pretty much correct. – vcsjones Dec 20 '12 at 20:42
  • @iambriansreed You should not dispose of the current context's site/web, that's correct. It's not that the items shouldn't be disposed, it's that you're not the one repsonsible for disposing it. The current context will create a site/web, hand that same object to a number of requests, and then handle disposing of it after a while. If you dispose of it early than all of the other requests that were given the same site/web will break, and have no knowledge of why. – Servy Dec 20 '12 at 20:52
  • @Servy Your comment has led me to my next question here: http://sharepoint.stackexchange.com/questions/54483/is-using-the-using-statement-to-close-random-webs-bad-practice. Thanks. – iambriansreed Dec 20 '12 at 21:06
0

See MSDN for a full explanation of exactly what "using" does: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Short answer is yes, since the Dispose is in a finally clause.

mletterle
  • 3,968
  • 1
  • 24
  • 24