Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

myCtrl.Parent = this vs. this.Controls.Add(myCtrl)

Sorry for the simple question...

I've tried both statements in some sample C# code and they seem to be equivalent.  Are they, or am I missing something?

Version 1) this.Controls.Add(myCtrl);

Version 2) myCtrl.Parent = this;


Thanks,

Charles

Charles Reich
Tuesday, December 09, 2003

Good question.

First of all, it's probably worth mentioning that we're talking about Windows Forms.  The Control.Parent property is read only for Web Forms so, as far as Web Forms are concerned, Controls.Add is the only way. 

Using IL DASM, it looks like there is no conceptual difference between setting Parent and called Controls.Add.  Setting the Parent property calls Controls.Add (with some checking for no change or a null parent). 

I'd guess that Controls.Add is the preferred technique since it cuts out the middleman and since it's more like the Web Forms technique. 

SomeBody
Tuesday, December 09, 2003

You are right.  I am working with Windows Forms.

Thanks for the response!

Charles Reich
Tuesday, December 09, 2003

*  Recent Topics

*  Fog Creek Home