What is the difference between :
Case 1:
var reader = cmd.ExecuteReader();
using(reader)
{
while(reader.read())
{
DoSomething(ref reader);
}
}
Case 2 :
using(var reader = cmd.ExecuteReader())
{
while(reader.read())
{
DoSomething(ref reader);
}
}
Case 1 : Doesn't produce any compiler errors but a warning line is shown under the reader variable inside the using
block and the warning says :
Possibly incorrect assignment to local 'variable' which is the argument to a using
or lock
statement. The Dispose
call or unlocking will happen on the original value of the local.
http://msdn.microsoft.com/en-us/library/zhdyhfk6%28v=vs.90%29.aspx
Case 2 : It produces a compiler error, due to the restricting the using
variable to readonly access.
Neglecting the need to use ref
, does this mean that in Case 1, the reader
variable won't be disposed, or at least disposed "as expected" ? Why is Case 1 doesn't produce any compiler errors but Case 2 does ?
Variables declared within a using
statement are read-only (they cannot be assigned after initialization).
Therefore, you cannot pass them as ref
parameters, since the point of ref
parameters is to be assigned.
In your first example, the variable is not declared in the using
statement, so it isn't read-only.
It gives a compiler warning for the same reason that the second variable is read-only.
The reason is that (as the warning states) the using
statement will only dispose the variable's original value.