why variable (myform) in using block treated as read-only and the compiler raise an error when I try to pass it as a reference to a function.
sample code:
using (Form myform = new Form)
{
myfunc(ref myform);
}
passing using variable to a function as ref will raise an error. thus the code above will raise an error.
Note : ‘readonly’ keyword is unrelated to my question.
I’m looking at an (outdated?) spec [1] right now.
15.13 says that variables that you declare in the resource acquisition part are readonly. That is:
works, but
doesn’t.
This answers part of the question (i.e. Why? Because it is part of the spec..), but I understand that this is not really satisfying. But why would you even want to do that?
Edit: After thinking about this, let me offer a possible explanation for this rule:
You have
and the compiler allows this. Now what if Foo needs a lot of unmanaged resources (maybe that’s the reason you wanted to use
usingin the first place)? After the using block you have no way to access this reference anymore. It wasn’t disposed, because you reassignedsomethingand forgot to handle it yourself. You don’t have a guarantee that the GC runs, at all. Or when. You just created a resource leak that is obscured and hidden.A final one, inspired by Henk’s link to Eric Lippert’s blog, which again just ends up throwing the spec at us:
In other words:
works, because this is expanded to
So in this case the fact that you have no influence over the
usingreference is just hidden from you and is exactly like in the previous case.1:http://www.ecma-international.org/publications/standards/Ecma-334.htm