Is returning a property of a child control in a getter infinitely recursive?
So ... it turns me on. I am using VS 2008 (C #).
I have some code that is infinitely recursive, but for the life of me, I cannot explain why (well, I guess). You can reproduce the problem by following these steps:
- Create a new class Form or UserControl. Add a child control (button, label, whatever) to it.
-
Open the code file. Override the Font property and return it and set the child to the Font Font property, i.e.
class MyForm { public override Font Font { get { return childControl.Font; } set { childControl.Font = value; } // not actually needed to reproduce } }
You only need a getter to return the child control property to reproduce the problem. After next build, don't open constructor for your form or UserControl, VS will crash.
-
Start your program. It will crash due to StackOverflow. This happens on
this.Controls.Add( childControl );
constructor file line. The Get () call on the Font property is recursive.
So, does anyone know why returning a child control to an override causes a stack overflow when the child is added to the Controls collection?
a source to share
This is because getting the control font involves looking at the parent font, which in your case includes looking at the child font, which includes looking at the original font, which includes ...
From MSDN :
The Font property is an ambient property. An external property is a control property that, if not set, is retrieved from the parent control.
a source to share