For example
using(var something = GetSomething())
{
something.DoSomething();
if(something.IsX()) return true;
}
return false;
For example
using(var something = GetSomething())
{
something.DoSomething();
if(something.IsX()) return true;
}
return false;
Yes, absolutely. The Dispose method is called however the using statement is executed, unless it was an abrupt whole-process termination. The most common cases are:
return within the blockBasically a using statement is mostly syntactic sugar for a try/finally block - and finally has all the same properties.
EDIT: From section 8.13 of the C# 4 specification:
A
usingstatement is stranslated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in atrystatement that includes afinallyclause. Thisfinallyclause disposes of the resource.
The finally statement is described in section 8.10 of the specification:
The statements of a
finallyblock are always executed when control leaves atrystatement. This is true whether the control transfer occurs as a result of normal execution; as a result of executing abreak,continue,gotoorreturnstatement; or as a result of propagating an exception out of thetrystatement.
Yes.
using is syntactic sugar for a try/finally block:
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block;
In the documentation on the finally block:
Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.
So, the using gets translated to try/finally, with .Dispose() in the finally part, ensuring that it is always executed no matter what happens in the try/catch.
Yes, using is a compiler feature, which expands to
try {
...
return ...;
}
finally {
foo.Dispose();
}
As far as I know the using block will dispose of the object as soon as it exits scope.
Eg, when true is returned, the next statement is outside of scope so the variable will be disposed.
I think as soon as the control will go out of {} dispose will be called so in short Yes
One point not yet mentioned is that while a "return" within a "using" block will call Dispose on the controlled variable, a "yield return" from within a "using" block within an iterator will not Dispose the controlled variable unless the IEnumerator associated with the iterator is Disposed.