Note the following code:
Control foo = null;
Control bar = null;
int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
test();
test();
Page.Controls.Add(foo);
}
void test()
{
i++;
bar = new Control();
bar.Controls.Add(new LiteralControl(i.ToString()));
if (foo == null)
{
foo = new Control();
foo.Controls.Add(bar);
}
}
When trying out the above code, I was suprised to see the result printed is '1' (not '2').
Im assuming this is because when i'm adding the control bar to foo, foo.Controls.Add() resolves the reference bar, rather than just storing the reference itself.
1) Can anyone confirm this is the case, or possibly elaborate?
2) I have a feeling if I was allowed to do foo.Controls.Add(ref bar); it would show '2', but obviously that syntax is illegal. Is it possible for this to be the case without major refactoring?