开发者

Why c# don't let to pass a using variable to a function as ref or out [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Passing an IDisposable object by reference causes an error?

Why doesn't C# allow passing a variable from a using block to a function as ref or out?

This is my code:

using (Form s = new Form())
{
    doSomthing(ref s);
}

T开发者_运维技巧he function ends before the using block ends, why doesn't C# let me pass s as ref or out parameter?


using variables are treated as readonly, as any reassignment is probably an error. Since ref allows reassignment, this would also be an issue. At the IL level, out is pretty-much identical to ref.

However, I doubt you need ref here; you are already passing a reference to the form, since it is a class. For reference-types, the main purpose of a ref would be to allow you to reassign the variable, and have the caller see the reassignment, i.e.

void doSomething(ref Form form)
{
    form = null; // the caller will see this change
}

it is not required if you are just talking to the form object:

void doSomething(Form form)
{
    form.Text = "abc"; // the caller will see this change even without ref
}

since it is the same form object.


The var in a using() statement is considered read-only inside the block. See § 8.13:

Local variables declared in a resource-acquisition are read-only, and must include an initializer. A compile-time error occurs if the embedded statement attempts to modify these local variables (by assignment or the ++ and -- operators) or pass them as ref or out parameters.

But note that this only applies to variables declared as part of the using statement, the following is legal (just not a good idea):

var f2 = System.IO.File.OpenText("");
using (f2)
{
    f2 = null;
}


One reason could be that doSomthing could make s refer to another Form instance than the one we have created. That could introduce a resource leak since the using block would then invoke Dispose on the Form instance that came from the method, and not the one created in the using block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜