Pay attention to 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 testing the above code, I was surprised to see that the result is printed: "1" (not "2").
I assume this is because when I add the control barto foo, it foo.Controls.Add()resolves the link bar, and not just saves the link.
1) Can someone confirm that this is so, or perhaps develop it?
2) I got a feeling that I am allowed to do foo.Controls.Add(ref bar);, it will show "2", but, obviously, this syntax is illegal. Is this possible without a lot of refactoring?