Does the C# `Using` statement close the variable if an error happens inside the using clause [duplicate]

StackOverflow https://stackoverflow.com/questions/13980058

Вопрос

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.

Это было полезно?

Решение

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();
}

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top